﻿/// <reference path="jquery-1.4.2-vsdoc.js" />

/**
* Copyright (c) 2005 - 2009, James Auldridge
* All rights reserved.
*
* Licensed under the BSD, MIT, and GPL (your choice!) Licenses:
*  http://code.google.com/p/cookies/wiki/License
*
*/
var jaaulde = window.jaaulde || {}; jaaulde.utils = jaaulde.utils || {}; jaaulde.utils.cookies = (function() {
    var cookies = []; var defaultOptions = { hoursToLive: null, path: '/', domain: null, secure: false }; var resolveOptions = function(options) {
        var returnValue; if (typeof options !== 'object' || options === null)
        { returnValue = defaultOptions; }
        else
        { returnValue = { hoursToLive: (typeof options.hoursToLive === 'number' && options.hoursToLive !== 0 ? options.hoursToLive : defaultOptions.hoursToLive), path: (typeof options.path === 'string' && options.path !== '' ? options.path : defaultOptions.path), domain: (typeof options.domain === 'string' && options.domain !== '' ? options.domain : defaultOptions.domain), secure: (typeof options.secure === 'boolean' && options.secure ? options.secure : defaultOptions.secure) }; }
        return returnValue;
    }; var expiresGMTString = function(hoursToLive)
    { var dateObject = new Date(); dateObject.setTime(dateObject.getTime() + (hoursToLive * 60 * 60 * 1000)); return dateObject.toGMTString(); }; var assembleOptionsString = function(options) {
        options = resolveOptions(options); return ((typeof options.hoursToLive === 'number' ? '; expires=' + expiresGMTString(options.hoursToLive) : '') + '; path=' + options.path +
(typeof options.domain === 'string' ? '; domain=' + options.domain : '') +
(options.secure === true ? '; secure' : ''));
    }; var splitCookies = function() {
        cookies = {}; var pair, name, value, separated = document.cookie.split(';'); for (var i = 0; i < separated.length; i = i + 1)
        { pair = separated[i].split('='); name = pair[0].replace(/^\s*/, '').replace(/\s*$/, ''); value = decodeURIComponent(pair[1]); cookies[name] = value; }
        return cookies;
    }; var constructor = function() { }; constructor.prototype.get = function(cookieName) {
        var returnValue; splitCookies(); if (typeof cookieName === 'string')
        { returnValue = (typeof cookies[cookieName] !== 'undefined') ? cookies[cookieName] : null; }
        else if (typeof cookieName === 'object' && cookieName !== null) {
            returnValue = {}; for (var item in cookieName) {
                if (typeof cookies[cookieName[item]] !== 'undefined')
                { returnValue[cookieName[item]] = cookies[cookieName[item]]; }
                else
                { returnValue[cookieName[item]] = null; }
            }
        }
        else
        { returnValue = cookies; }
        return returnValue;
    }; constructor.prototype.filter = function(cookieNameRegExp) {
        var returnValue = {}; splitCookies(); if (typeof cookieNameRegExp === 'string')
        { cookieNameRegExp = new RegExp(cookieNameRegExp); }
        for (var cookieName in cookies) {
            if (cookieName.match(cookieNameRegExp))
            { returnValue[cookieName] = cookies[cookieName]; }
        }
        return returnValue;
    }; constructor.prototype.set = function(cookieName, value, options) {
        if (typeof value === 'undefined' || value === null) {
            if (typeof options !== 'object' || options === null)
            { options = {}; }
            value = ''; options.hoursToLive = -8760;
        }
        var optionsString = assembleOptionsString(options); document.cookie = cookieName + '=' + encodeURIComponent(value) + optionsString;
    }; constructor.prototype.del = function(cookieName, options) {
        var allCookies = {}; if (typeof options !== 'object' || options === null)
        { options = {}; }
        if (typeof cookieName === 'boolean' && cookieName === true)
        { allCookies = this.get(); }
        else if (typeof cookieName === 'string')
        { allCookies[cookieName] = true; }
        for (var name in allCookies) {
            if (typeof name === 'string' && name !== '')
            { this.set(name, null, options); }
        }
    }; constructor.prototype.test = function() {
        var returnValue = false, testName = 'cT', testValue = 'data'; this.set(testName, testValue); if (this.get(testName) === testValue)
        { this.del(testName); returnValue = true; }
        return returnValue;
    }; constructor.prototype.setOptions = function(options) {
        if (typeof options !== 'object')
        { options = null; }
        defaultOptions = resolveOptions(options);
    }; return new constructor();
})(); (function() {
    if (window.jQuery) {
        (function($) {
            $.cookies = jaaulde.utils.cookies; var extensions = { cookify: function(options) {
                return this.each(function() {
                    var i, resolvedName = false, resolvedValue = false, name = '', value = '', nameAttrs = ['name', 'id'], nodeName, inputType; for (i in nameAttrs) {
                        if (!isNaN(i)) {
                            name = $(this).attr(nameAttrs[i]); if (typeof name === 'string' && name !== '')
                            { resolvedName = true; break; }
                        }
                    }
                    if (resolvedName) {
                        nodeName = this.nodeName.toLowerCase(); if (nodeName !== 'input' && nodeName !== 'textarea' && nodeName !== 'select' && nodeName !== 'img')
                        { value = $(this).html(); resolvedValue = true; }
                        else {
                            inputType = $(this).attr('type'); if (typeof inputType === 'string' && inputType !== '')
                            { inputType = inputType.toLowerCase(); }
                            if (inputType !== 'radio' && inputType !== 'checkbox')
                            { value = $(this).val(); resolvedValue = true; }
                        }
                        if (resolvedValue) {
                            if (typeof value !== 'string' || value === '')
                            { value = null; }
                            $.cookies.set(name, value, options);
                        }
                    }
                });
            }, cookieFill: function() {
                return this.each(function() {
                    var i, resolvedName = false, name = '', value, nameAttrs = ['name', 'id'], iteration = 0, nodeName; for (i in nameAttrs) {
                        if (!isNaN(i)) {
                            name = $(this).attr(nameAttrs[i]); if (typeof name === 'string' && name !== '')
                            { resolvedName = true; break; }
                        }
                    }
                    if (resolvedName) {
                        value = $.cookies.get(name); if (value !== null) {
                            nodeName = this.nodeName.toLowerCase(); if (nodeName === 'input' || nodeName === 'textarea' || nodeName === 'select')
                            { $(this).val(value); }
                            else
                            { $(this).html(value); }
                        }
                    }
                    iteration = 0;
                });
            }, cookieBind: function(options) {
                return this.each(function() {
                    $(this).cookieFill().change(function()
                    { $(this).cookify(options); });
                });
            }
            }; $.each(extensions, function(i)
            { $.fn[i] = this; });
        })(window.jQuery);
    }
})();
function isDateObject(obj) {
    if (isNaN(obj) == false && String(obj).indexOf(" ") >= 0)
        return true;
    else
        return false;
}

//scrollFollow by bestshuai
(function($) {
    $.fn.scrollFollow = function(options) {
        if (this.attr('scrollFollowInited') == 'true') return;
        this.attr('scrollFollowInited', 'true');
        if (!options || !options.offset)
            options = { offset: 0 };
        this.attr('orgPos', this.css('position'));
        this.attr('orgTop', this.css('top'));
        this.attr('orgOffset', this.offset().top);
        this.attr('isfixed', 'false');
        var obj = this;
        $(window).scroll(function() {
            var sh = parseInt(Math.max(document.body.scrollTop, document.documentElement.scrollTop), 10);
            if (obj.attr('isfixed') == 'false' && sh > obj.attr('orgOffset')) {
                //固顶在屏幕上,不随滚动条变化
                obj.parent().css("min-height", obj.parent().height());
                obj.width(obj.width());
                if ($.browser.msie && $.browser.version <= '6.0') {
                    obj.css('position', 'absolute');
                }
                else {
                    obj.css('position', 'fixed');
                    obj.css('top', options.offset + 'px');
                }
                obj.attr('isfixed', 'true');
            }
            else if (obj.attr('isfixed') && sh < obj.attr('orgOffset')) {
                obj.css('position', obj.attr('orgPos'));
                obj.css('top', obj.attr('orgTop'));
                obj.attr('isfixed', 'false');
            }
            if (obj.attr('isfixed') && $.browser.msie && $.browser.version <= '6.0' && sh > obj.attr('orgOffset')) {
                obj.css('top', (sh + options.offset) + 'px');
            }
        });
    };
})(jQuery);

//scrollFix by bestshuai
(function($) {
    $.fn.scrollFix = function(options) {
        if (this.attr('scrollFixInited') == 'true') return;
        this.attr('scrollFixInited', 'true');
        if (!options || !options.offset)
            options = { offset: 0 };
        this.attr('orgPos', this.css('position'));
        this.attr('orgTop', this.css('top'));
        this.attr('orgOffset', this.offset().top);
        this.attr('isfixed', 'false');
        var obj = this;
        var onscroll = function(obj) {
            var sh = parseInt(Math.max(document.body.scrollTop, document.documentElement.scrollTop), 10);
            if (obj.attr('isfixed') == 'false') {
                //固顶在屏幕上,不随滚动条变化
                if ($.browser.msie && $.browser.version <= '6.0') {
                    obj.css('position', 'absolute');
                }
                else {
                    obj.css('position', 'fixed');
                    obj.css('top', options.offset + 'px');
                }
                obj.attr('isfixed', 'true');
            }
            if (obj.attr('isfixed') && $.browser.msie && $.browser.version <= '6.0') {
                obj.css('top', (sh + options.offset) + 'px');
            }
        };
        $(window).scroll(function() { onscroll(obj); });
        onscroll(obj);
    };
})(jQuery);

/*
Date Input 1.2.1
Requires jQuery version: >= 1.2.6

Copyright (c) 2007-2008 Jonathan Leighton & Torchbox Ltd

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

DateInput = (function($) {

    function DateInput(el, opts) {
        if ($(el).attr('DateInputInited') == 'true') return;
        $(el).attr('DateInputInited', 'true');
        if (typeof (opts) != "object") opts = {};
        $.extend(this, DateInput.DEFAULT_OPTS, opts);

        this.input = $(el);
        this.bindMethodsToObj("show", "hide", "hideIfClickOutside", "keydownHandler", "selectDate");

        this.build();
        this.selectDate();
        this.hide();
        var oThis = this;
        this.input.change(function() { oThis.input.val(oThis.dateToString(oThis.stringToDate(oThis.input.val()))); });
    };
    DateInput.DEFAULT_OPTS = {
        month_names: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        short_month_names: ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"],
        short_day_names: ["日", "一", "二", "三", "四", "五", "六"],
        start_of_week: 0
    };
    DateInput.prototype = {
        build: function() {
            var monthNav = $('<p class="month_nav">' +
      '<span class="button prev" title="[Page-Up]">&#171;</span>' +
      ' <span class="month_name"></span> ' +
      '<span class="button next" title="[Page-Down]">&#187;</span>' +
      '</p>');
            this.monthNameSpan = $(".month_name", monthNav);
            $(".prev", monthNav).mousedown(this.bindToObj(function() { this.moveMonthBy(-1); }));
            $(".next", monthNav).mousedown(this.bindToObj(function() { this.moveMonthBy(1); }));

            var yearNav = $('<p class="year_nav">' +
      '<span class="button prev" title="[Ctrl+Page-Up]">&#171;</span>' +
      ' <span class="year_name"></span> ' +
      '<span class="button next" title="[Ctrl+Page-Down]">&#187;</span>' +
      '</p>');
            this.yearNameSpan = $(".year_name", yearNav);
            $(".prev", yearNav).mousedown(this.bindToObj(function() { this.moveMonthBy(-12); }));
            $(".next", yearNav).mousedown(this.bindToObj(function() { this.moveMonthBy(12); }));

            var nav = $('<div class="ds_nav"></div>').append(monthNav, yearNav);

            var tableShell = "<table><thead><tr>";
            $(this.adjustDays(this.short_day_names)).each(function() {
                tableShell += "<th>" + this + "</th>";
            });
            tableShell += "</tr></thead><tbody></tbody></table>";

            this.dateSelector = this.rootLayers = $('<div class="date_selector"></div>').append(nav, tableShell).insertAfter(this.input);

            if ($.browser.msie && $.browser.version < 7) {

                this.ieframe = $('<iframe class="date_selector_ieframe" frameborder="0" src="#"></iframe>').insertBefore(this.dateSelector);
                this.rootLayers = this.rootLayers.add(this.ieframe);

                $(".button", nav).mouseover(function() { $(this).addClass("hover") });
                $(".button", nav).mouseout(function() { $(this).removeClass("hover") });
            };

            this.tbody = $("tbody", this.dateSelector);

            this.input.change(this.bindToObj(function() { this.selectDate(); }));
            this.selectDate();
        },

        selectMonth: function(date) {
            var newMonth = new Date(date.getFullYear(), date.getMonth(), 1);

            if (!this.currentMonth || !(this.currentMonth.getFullYear() == newMonth.getFullYear() &&
                                this.currentMonth.getMonth() == newMonth.getMonth())) {

                this.currentMonth = newMonth;

                var rangeStart = this.rangeStart(date), rangeEnd = this.rangeEnd(date);
                var numDays = this.daysBetween(rangeStart, rangeEnd);
                var dayCells = "";

                for (var i = 0; i <= numDays; i++) {
                    var currentDay = new Date(rangeStart.getFullYear(), rangeStart.getMonth(), rangeStart.getDate() + i, 12, 00);

                    if (this.isFirstDayOfWeek(currentDay)) dayCells += "<tr>";

                    if (currentDay.getMonth() == date.getMonth()) {
                        dayCells += '<td class="selectable_day" date="' + this.dateToString(currentDay) + '">' + currentDay.getDate() + '</td>';
                    } else {
                        dayCells += '<td class="unselected_month" date="' + this.dateToString(currentDay) + '">' + currentDay.getDate() + '</td>';
                    };

                    if (this.isLastDayOfWeek(currentDay)) dayCells += "</tr>";
                };
                this.tbody.empty().append(dayCells);

                this.monthNameSpan.empty().append(this.monthName(date));
                this.yearNameSpan.empty().append(this.currentMonth.getFullYear());

                $(".selectable_day", this.tbody).mousedown(this.bindToObj(function(event) {
                    this.changeInput($(event.target).attr("date"));
                }));

                $("td[date=" + this.dateToString(new Date()) + "]", this.tbody).addClass("today");

                $("td.selectable_day", this.tbody).mouseover(function() { $(this).addClass("hover") });
                $("td.selectable_day", this.tbody).mouseout(function() { $(this).removeClass("hover") });
            };

            $('.selected', this.tbody).removeClass("selected");
            $('td[date=' + this.selectedDateString + ']', this.tbody).addClass("selected");
        },

        selectDate: function(date) {
            if (typeof (date) == "undefined") {
                date = this.stringToDate(this.input.val());
            };
            if (!date) date = new Date();

            this.selectedDate = date;
            this.selectedDateString = this.dateToString(this.selectedDate);
            this.selectMonth(this.selectedDate);
        },

        changeInput: function(dateString) {
            this.input.val(dateString).change();
            this.hide();
            this.input.blur();
        },

        show: function(event) {
            this.rootLayers.css("display", "block");
            $([window, document.body]).mousedown(this.hideIfClickOutside);
            this.input.unbind("focus", this.show);
            $(document.body).keydown(this.keydownHandler);
            this.setPosition();
            if (this.input.val() == "") {
                //this.input.val(this.dateToString(new Date()));
                this.input[0].select();
            }
        },

        hide: function() {
            this.rootLayers.css("display", "none");
            $([window, document.body]).unbind("mousedown", this.hideIfClickOutside);
            this.input.focus(this.show);
            $(document.body).unbind("keydown", this.keydownHandler);
        },

        hideIfClickOutside: function(event) {
            if (event.target != this.input[0] && !this.insideSelector(event)) {
                this.hide();
            };
        },

        insideSelector: function(event) {
            var offset = this.dateSelector.position();
            offset.right = offset.left + this.dateSelector.outerWidth();
            offset.bottom = offset.top + this.dateSelector.outerHeight();

            return event.pageY < offset.bottom &&
				event.pageY > offset.top &&
				event.pageX < offset.right &&
				event.pageX > offset.left;
        },

        keydownHandler: function(event) {
            switch (event.keyCode) {
                case 9:
                case 27:
                    this.hide();
                    return;
                    break;
                case 13:
                    this.changeInput(this.selectedDateString);
                    break;
                case 33:
                    this.moveDateMonthBy(event.ctrlKey ? -12 : -1);
                    break;
                case 34:
                    this.moveDateMonthBy(event.ctrlKey ? 12 : 1);
                    break;
                case 38:
                    this.moveDateBy(-7);
                    break;
                case 40:
                    this.moveDateBy(7);
                    break;
                case 37:
                    this.moveDateBy(-1);
                    break;
                case 39:
                    this.moveDateBy(1);
                    break;
                default:
                    return;
            }
            event.preventDefault();
        },

        stringToDate: function(string) {
            try {
                var matches;
                //if (matches = string.match(/^(\d{1,2}) ([^\s]+) (\d{4,4})$/)) {
                if (matches = string.match(/^(\d{4,4})-(\d{1,2})-(\d{1,2})$/)) {
                    return new Date(matches[1], parseInt(matches[2], 10) - 1, parseInt(matches[3], 10), 12, 00);
                } else {
                    return null;
                };
            }
            catch (e) {
                return null;
            }
        },

        dateToString: function(date) {
            //return date.getDate() + " " + this.short_month_names[date.getMonth()] + " " + date.getFullYear();
            try {
                var mon = (date.getMonth() + 1);
                if (mon < 10) mon = '0' + mon;
                var day = (date.getDate());
                if (day < 10) day = '0' + day;
                return date.getFullYear() + "-" + mon + "-" + day;
            }
            catch (e) {
                return '';
            }
        },

        setPosition: function() {
            var offset = this.input.offset();
            var offsetP = this.input.offsetParent().offset();
            //alert('left:'+offset.left + ', top:'+ offset.top);
            //alert('p_left:'+offsetP.left + ', p_top:'+ offsetP.top);
            //alert(this.input.css('border-width'));
            this.rootLayers.css({
                //top: offset.top + this.input.outerHeight(),
                //left: offset.left
                top: offset.top - offsetP.top + this.input.height() + Number(this.input.css('border-width').replace('px', '')) * 2 + 2,
                left: offset.left - offsetP.left
            });

            if (this.ieframe) {
                this.ieframe.css({
                    width: this.dateSelector.outerWidth(),
                    height: this.dateSelector.outerHeight()
                });
            };
        },

        moveDateBy: function(amount) {
            var newDate = new Date(this.selectedDate.getFullYear(), this.selectedDate.getMonth(), this.selectedDate.getDate() + amount);
            this.selectDate(newDate);
        },

        moveDateMonthBy: function(amount) {
            var newDate = new Date(this.selectedDate.getFullYear(), this.selectedDate.getMonth() + amount, this.selectedDate.getDate());
            if (newDate.getMonth() == this.selectedDate.getMonth() + amount + 1) {

                newDate.setDate(0);
            };
            this.selectDate(newDate);
        },

        moveMonthBy: function(amount) {
            var newMonth = new Date(this.currentMonth.getFullYear(), this.currentMonth.getMonth() + amount, this.currentMonth.getDate());
            this.selectMonth(newMonth);
        },

        monthName: function(date) {
            return this.month_names[date.getMonth()];
        },

        bindToObj: function(fn) {
            var self = this;
            return function() { return fn.apply(self, arguments) };
        },

        bindMethodsToObj: function() {
            for (var i = 0; i < arguments.length; i++) {
                this[arguments[i]] = this.bindToObj(this[arguments[i]]);
            };
        },

        indexFor: function(array, value) {
            for (var i = 0; i < array.length; i++) {
                if (value == array[i]) return i;
            };
        },

        monthNum: function(month_name) {
            return this.indexFor(this.month_names, month_name);
        },

        shortMonthNum: function(month_name) {
            return this.indexFor(this.short_month_names, month_name);
        },

        shortDayNum: function(day_name) {
            return this.indexFor(this.short_day_names, day_name);
        },

        daysBetween: function(start, end) {
            start = Date.UTC(start.getFullYear(), start.getMonth(), start.getDate());
            end = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate());
            return (end - start) / 86400000;
        },

        changeDayTo: function(dayOfWeek, date, direction) {
            var difference = direction * (Math.abs(date.getDay() - dayOfWeek - (direction * 7)) % 7);
            return new Date(date.getFullYear(), date.getMonth(), date.getDate() + difference);
        },

        rangeStart: function(date) {
            return this.changeDayTo(this.start_of_week, new Date(date.getFullYear(), date.getMonth()), -1);
        },

        rangeEnd: function(date) {
            return this.changeDayTo((this.start_of_week - 1) % 7, new Date(date.getFullYear(), date.getMonth() + 1, 0), 1);
        },

        isFirstDayOfWeek: function(date) {
            return date.getDay() == this.start_of_week;
        },

        isLastDayOfWeek: function(date) {
            return date.getDay() == (this.start_of_week - 1) % 7;
        },

        adjustDays: function(days) {
            var newDays = [];
            for (var i = 0; i < days.length; i++) {
                newDays[i] = days[(i + this.start_of_week) % 7];
            };
            return newDays;
        }
    };

    $.fn.setDate = function(date) {
        //        var y = date.getFullYear();
        //        var m = date.getMonth() + 1;
        //        var d = date.getDate();
        //        $(this).val(y + '-' + (m.length < 2 ? '0' + m : m) + '-' + (d.length < 2 ? '0' + d : d));
        $(this).val(date.format('yyyy-MM-dd'));
    }

    $.fn.getDate = function() {
        var val = $(this).val();
        if (val && val.match(/[0-9]{4}-[0-9]{2}-[0-9]{2}/)) {
            var parts = val.split('-');
            var date = $.parseJSON($.toJSON(new Date(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1, parseInt(parts[2], 10))));
            return date;
        }
        else {
            return null;
        }
    }

    $.fn.date_input = function(opts) {
        return this.each(function() { new DateInput(this, opts); });
    };
    $.date_input = { initialize: function(opts) {
        $("input.date_input").date_input(opts);
    }
    };

    return DateInput;
})(jQuery);

/*	MonthInput 
*	spectorye
*	2010-5-4
*	参考DateInput
*/
MonthInput = (function($) {
    function MonthInput(el, opts) {
        if ($(el).attr('MonthInputInited') == 'true') return;
        $(el).attr('MonthInputInited', 'true');
        if (typeof (opts) != "object") opts = {};
        $.extend(this, MonthInput.DEFAULT_OPTS, opts);
        this.input = $(el);
        this.currMonth = new Date();
        this.bindMethodsToObj("show", "hide", "hideIfClickOutside");
        this.build();
        //this.moveYearBy(0);
        this.hide();
        var oThis = this;
        this.input.change(function() { oThis.input.val(oThis.dateToString(oThis.stringToDate(oThis.input.val()))); });
        $('td', this.dateSelector).mousedown(function() {
            var m = $(this).attr('m');
            this.currMonth = new Date(oThis.yearNameSpan.text(), m, 1);
            if (m.length < 2) {
                m = '0' + m;
            }
            oThis.input.val(oThis.yearNameSpan.text() + m);
            oThis.hide();
        });
    };
    MonthInput.DEFAULT_OPTS = {
        month_num: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
    };
    MonthInput.prototype = {
        build: function() {
            var yearNav = $('<p class="year_nav">' +
				'<span class="button prev" title="Previous Year">&#171;</span>' +
				'<span class="year_name">' + new Date().getFullYear() + '</span> ' +
				'<span class="button next" title="Next Year">&#187;</span>' +
				'</p>');
            this.yearNameSpan = $(".year_name", yearNav);
            $(".prev", yearNav).mousedown(this.bindToObj(function() { this.moveYearBy(-1); return false; }));
            $(".next", yearNav).mousedown(this.bindToObj(function() { this.moveYearBy(1); return false; }));
            var nav = $('<div class="ds_nav"></div>').append(yearNav);
            var tds = '';
            $(MonthInput.DEFAULT_OPTS.month_num).each(function(i, item) {
                if (item == 6) {
                    tds += '<td m="' + item + '">' + item + '</td></tr><tr>';
                }
                else {
                    tds += '<td m="' + item + '">' + item + '</td>';
                }
            });
            var tableShell = "<table><tbody><tr>" + tds + "</tr></tbody></table>";
            this.dateSelector = this.rootLayers = $('<div class="month_selector"></div>').append(nav, tableShell).insertAfter(this.input);
            if ($.browser.msie && $.browser.version < 7) {

                this.ieframe = $('<iframe class="date_selector_ieframe" frameborder="0" src="#"></iframe>').insertBefore(this.dateSelector);
                this.rootLayers = this.rootLayers.add(this.ieframe);

                $(".button", nav).mouseover(function() { $(this).addClass("hover") });
                $(".button", nav).mouseout(function() { $(this).removeClass("hover") });
            };
            this.tbody = $("tbody", this.dateSelector);
        },
        moveYearBy: function(y) {
            var currYear = parseInt(this.yearNameSpan.text(), 10);
            if (y != 0) {
                currYear = currYear + y;
                this.yearNameSpan.text(currYear);
            }
            if (currYear == new Date().getFullYear()) {
                var mon = (new Date().getMonth() + 1);
                $('td.tomonth').removeClass('tomonth');
                $('td[m="' + mon + '"]', this.dateSelector).removeClass().addClass('tomonth');
            }
            else {
                $('td.tomonth').removeClass('tomonth');
            }
            if (currYear == this.currMonth.getFullYear()) {
                var mon = (this.currMonth.getMonth() + 1);
                $('td.selected').removeClass('selected');
                $('td[m="' + mon + '"]', this.dateSelector).removeClass().addClass('selected');
            }
            else {
                $('td.selected').removeClass('selected');
            }
        },
        show: function(event) {
            this.rootLayers.css("display", "block");
            $([window, document.body]).mousedown(this.hideIfClickOutside);
            this.input.unbind("focus", this.show);
            this.setPosition();
            if (this.input.val() == "") {
                this.input.val(this.dateToString(new Date()));
                this.input[0].select();
            }
            this.currMonth = this.stringToDate(this.input.val());
            $('td.selected').removeClass('selected');
            if (this.currMonth != null) {
                var mon = (this.currMonth.getMonth() + 1);
                $('td[m="' + mon + '"]', this.dateSelector).removeClass().addClass('selected');
                var y = this.currMonth.getFullYear();
                if (String(y) != this.yearNameSpan.text()) {
                    this.yearNameSpan.text(y);
                }
                this.moveYearBy(0);
            }
        },
        hide: function() {
            this.rootLayers.css("display", "none");
            $([window, document.body]).unbind("mousedown", this.hideIfClickOutside);
            this.input.focus(this.show);
        },
        hideIfClickOutside: function(event) {
            if (event.target != this.input[0] && !this.insideSelector(event)) {
                this.hide();
            };
        },
        insideSelector: function(event) {
            var offset = this.dateSelector.position();
            offset.right = offset.left + this.dateSelector.outerWidth();
            offset.bottom = offset.top + this.dateSelector.outerHeight();

            return event.pageY < offset.bottom &&
				event.pageY > offset.top &&
				event.pageX < offset.right &&
				event.pageX > offset.left;
        },
        setPosition: function() {
            var offset = this.input.offset();
            var offsetP = this.input.offsetParent().offset();
            this.rootLayers.css({
                top: offset.top - offsetP.top + this.input.height() + Number(this.input.css('border-width').replace('px', '')) * 2 + 3,
                left: offset.left - offsetP.left
            });
            if (this.ieframe) {
                this.ieframe.css({
                    width: this.dateSelector.outerWidth(),
                    height: this.dateSelector.outerHeight()
                });
            };
        },
        bindToObj: function(fn) {
            var self = this;
            return function() { return fn.apply(self, arguments) };
        },
        bindMethodsToObj: function() {
            for (var i = 0; i < arguments.length; i++) {
                this[arguments[i]] = this.bindToObj(this[arguments[i]]);
            };
        },
        stringToDate: function(string) {
            try {
                var matches;
                if (matches = string.match(/^(\d{4,4})(\d{2,2})$/)) {
                    return new Date(matches[1], parseInt(matches[2], 10) - 1, 1, 12, 00);
                } else {
                    return null;
                };
            }
            catch (e) {
                return null;
            }
        },
        dateToString: function(date) {
            try {
                var mon = (date.getMonth() + 1);
                if (mon < 10) mon = '0' + mon;
                return String(date.getFullYear()) + mon;
            }
            catch (e) {
                return '';
            }
        }
    };

    $.fn.month_input = function(opts) {
        return this.each(function() { new MonthInput(this, opts); });
    };
    $.month_input = { initialize: function(opts) {
        $("input.date_input").month_input(opts);
    }
    };

    return MonthInput;
})(jQuery);

/*	MoneyInput 
*	spectorye
*	2010-5-7
*	参考MonthInput
*/
MoneyInput = (function($) {
    function MoneyInput(el) {
        this.input = $(el);
        var oThis = this;
        this.input.focus(function() {
            //oThis.input.val(oThis.stringToMoney(oThis.input.val()));
            if (oThis.input.val() == '') {
                oThis.input.val('0.00');
            }
            oThis.input.get()[0].select();
        });
        this.input.blur(function() {
            oThis.input.val(oThis.moneyToString(oThis.stringToMoney(oThis.input.val())));
        });
    };

    MoneyInput.prototype = {
        stringToMoney: function(string) {
            string = string.replace(/,/g, '');
            if (String(parseFloat(string)) != 'NaN') {
                return Math.round(parseFloat(string) * 100) / 100;
            }
            else {
                return 0.00;
            }
        },
        moneyToString: function(eValue) {
            try {
                eValue = new Number(eValue).toFixed(2);
                var intPart = "";
                var decPart = "";
                if (eValue.indexOf(",") >= 0) {
                    eValue = eValue.replace(/,/g, "");
                }
                if (eValue.indexOf(".") >= 0) {
                    intPart = eValue.split(".")[0];
                    decPart = eValue.split(".")[1];
                }
                else {
                    intPart = eValue;
                }
                var num = intPart + "";
                var re = /(-?\d+)(\d{3})/
                while (re.test(num)) {
                    num = num.replace(re, "$1,$2")
                }
                if (eValue.indexOf(".") >= 0) {
                    eValue = num + "." + decPart;
                }
                else {
                    eValue = num;
                }
                return eValue;
            }
            catch (e) {
                return '';
            }
        }
    };

    $.fn.money_input = function() {
        return this.each(function() { new MoneyInput(this); });
    };
})(jQuery);
/*
* Autocomplete - jQuery plugin 1.0.2
*
* Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
* Revision: $ID: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $
* bestshuai 2009.8 : patch for chinese input and multiselect
*/

; (function($) {
    /**
    * @author 全冠清
    */
    $.fn.extend({
        endInsPoint: function() {
            var elem = this[0];
            if (elem && (elem.tagName == "TEXTAREA" || elem.type.toLowerCase() == "text")) {
                if ($.browser.msie) {
                    var rng = elem.createTextRange();
                    rng.moveStart("character", elem.value.length);
                    rng.select();
                } else {
                    elem.selectionEnd = elem.value.length;
                    elem.selectionStart = elem.value.length;
                }
            }
        }
    });

    $.fn.extend({
        autocomplete: function(urlOrData, options) {
            if (this.attr('isautocompleteinited') == 'true') return;
            this.attr('isautocompleteinited', 'true');
            var isUrl = typeof urlOrData == "string";
            options = $.extend({}, $.Autocompleter.defaults, {
                url: isUrl ? urlOrData : null,
                data: isUrl ? null : urlOrData,
                delay: isUrl ? $.Autocompleter.defaults.delay : 10,
                max: options && !options.scroll ? 10 : 500
            }, options);

            // if highlight is set to false, replace it with a do-nothing function
            options.highlight = options.highlight || function(value) { return value; };

            // if the formatMatch option is not specified, then use formatItem for backwards compatibility
            options.formatMatch = options.formatMatch || options.formatItem;

            return this.each(function() {
                new $.Autocompleter(this, options);
            });
        },
        result: function(handler) {
            return this.bind("result", handler);
        },
        search: function(handler) {
            return this.trigger("search", [handler]);
        },
        showList: function(q) {
            return this.trigger("showList", [q]);
        },
        flushCache: function() {
            return this.trigger("flushCache");
        },
        setOptions: function(options) {
            return this.trigger("setOptions", [options]);
        },
        unautocomplete: function() {
            return this.trigger("unautocomplete");
        }
    });

    $.Autocompleter = function(input, options) {

        var KEY = {
            UP: 38,
            DOWN: 40,
            DEL: 46,
            TAB: 9,
            RETURN: 13,
            ESC: 27,
            COMMA: 188,
            PAGEUP: 33,
            PAGEDOWN: 34,
            BACKSPACE: 8
        };

        // Create $ object for input element
        var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

        var timeout;
        var previousValue = "";
        var cache = $.Autocompleter.Cache(options);
        var hasFocus = 0;
        var lastKeyPressCode;
        var config = {
            mouseDownOnSelect: false
        };
        var select = $.Autocompleter.Select(options, input, selectCurrent, config);

        var blockSubmit;

        // prevent form submit in opera when selecting with return key
        $.browser.opera && $(input.form).bind("submit.autocomplete", function() {
            if (blockSubmit) {
                blockSubmit = false;
                return false;
            }
        });

        // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
        $input.bind("keydown.autocomplete", function(event) {
            // track last key pressed
            if (event.keyCode == 0 && event.charCode) {
                event.keyCode = event.charCode;
            }
            lastKeyPressCode = event.keyCode;
            // 强制处理分号，在firefox和ie下分别是59和186 PS: ms真讨厌，一个键还有几个码
            if (options.multiple && (event.keyCode == 59 || event.keyCode == 186)) {
                var val = $input.val();
                if ($.trim(val) == '' || val.charAt(val.length - 1) == options.multipleSeparator) {
                    return false;
                }
                event.keyCode = KEY.RETURN;
            }
            switch (event.keyCode) {

                case KEY.UP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.prev();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.DOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.next();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEUP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageUp();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEDOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageDown();
                    } else {
                        onChange(0, true);
                    }
                    break;

                // matches also semicolon                                                                                                                       
                case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
                case KEY.TAB:
                case KEY.RETURN:
                    if (selectCurrent()) {
                        // stop default to prevent a form submit, Opera needs special handling
                        event.preventDefault();
                        blockSubmit = true;
                        return false;
                    }
                    break;

                case KEY.ESC:
                    select.hide();
                    break;
                /*
                default:
                clearTimeout(timeout);
                timeout = setTimeout(onChange, options.delay);
                break;
                */ 
            }
        }).bind('keyup.autocomplete', function(event) {//for firefox
            if (event.keyCode != KEY.RETURN && event.keyCode != 59 && event.keyCode != 186) {
                clearTimeout($input.attr('keyupTimeout'));
                $input.attr('keyupTimeout', setTimeout(onChange, options.delay));
            }
        }).focus(function() {
            // track whether the field has focus, we shouldn't process any
            // results if the field no longer has focus
            hasFocus++;
        }).blur(function() {
            hasFocus = 0;
            if (!config.mouseDownOnSelect) {
                hideResults();
            }
        }).click(function() {
            // show select when clicking in a focused field
            if (hasFocus++ > 1 && !select.visible()) {
                onChange(0, true);
            }
        }).bind("search", function() {
            // TODO why not just specifying both arguments?
            var fn = (arguments.length > 1) ? arguments[1] : null;
            function findValueCallback(q, data) {
                var result;
                if (data && data.length) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].result.toLowerCase() == q.toLowerCase()) {
                            result = data[i];
                            break;
                        }
                    }
                }
                if (typeof fn == "function") fn(result);
                else $input.trigger("result", result && [result.data, result.value]);
            }
            $.each(trimWords($input.val()), function(i, value) {
                request(value, findValueCallback, findValueCallback);
            });
        }).bind("flushCache", function() {
            cache.flush();
        }).bind("setOptions", function() {
            $.extend(options, arguments[1]);
            // if we've updated the data, repopulate
            if ("data" in arguments[1])
                cache.populate();
        }).bind("unautocomplete", function() {
            select.unbind();
            $input.unbind();
            $input.attr('isautocompleteinited', 'false');
            $(input.form).unbind(".autocomplete");
        }).bind("showList", function() { showList(arguments[1]); });


        function selectCurrent() {
            var selected = select.selected();
            if (!selected)
                return false;

            var v = selected.result;
            previousValue = v;

            if (options.multiple) {
                var text = $.trim($input.val());
                if (text.lastIndexOf(options.multipleSeparator) == (text.length - 1)) {
                    text += v;
                    $input.val(text);
                }
                var words = trimWords($input.val());
                if (words.length > 1) {
                    var prewords = words.slice(0, words.length - 1);
                    var isfound = false;
                    for (var i = prewords.length - 1; i >= 0; i--) {
                        if (prewords[i] == v) {
                            isfound = true;
                            break;
                        }
                    }
                    if (isfound == false) {
                        v = prewords.join(options.multipleSeparator) + options.multipleSeparator + v;
                    }
                    else {
                        v = prewords.join(options.multipleSeparator);
                    }
                }
                v += options.multipleSeparator;
            }

            $input.val(v);
            hideResultsNow();
            $input.trigger("result", [selected.data, selected.value]);
            return true;
        }

        function showList(q) {
            //取消可能在途的blur的hideResults
            clearTimeout(timeout);
            if (select.visible()) {
                $input.blur();
            }
            else {
                $input.focus();
                request(q, receiveData, hideResultsNow);
            }
        }

        function onChange(crap, skipPrevCheck) {
            if (lastKeyPressCode == KEY.DEL) {
                select.hide();
                return;
            }

            var currentValue = $input.val();

            if (!skipPrevCheck && currentValue == previousValue)
                return;

            if (options.multiple && currentValue.charAt(currentValue.length - 1) == options.multipleSeparator) {
                select.hide();
                return;
            }

            previousValue = currentValue;
            currentValue = lastWord(currentValue);
            if (currentValue.length >= options.minChars) {
                $input.addClass(options.loadingClass);
                if (!options.matchCase)
                    currentValue = currentValue.toLowerCase();
                request(currentValue, receiveData, hideResultsNow);
            } else {
                stopLoading();
                select.hide();
            }
        };

        function trimWords(value) {
            if (!value) {
                return [""];
            }
            var words = value.split(options.multipleSeparator);
            var result = [];
            $.each(words, function(i, value) {
                if ($.trim(value))
                    result[i] = $.trim(value);
            });
            return result;
        }

        function lastWord(value) {
            if (!options.multiple)
                return value;
            var words = trimWords(value);
            if (words.length > 0) {
                return words[words.length - 1];
            }
            else {
                return "";
            }
        }

        // fills in the input box w/the first match (assumed to be the best match)
        // q: the term entered
        // sValue: the first matching result
        function autoFill(q, sValue) {
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            // if the last user key pressed was backspace, don't autofill
            if (options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE) {
                // fill in the value (keep the case the user has typed)
                $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
                // select the portion of the value not typed by the user (so the next character will erase)
                $.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
            }
        };

        function hideResults() {
            clearTimeout(timeout);
            select.hide();
            timeout = setTimeout(hideResultsNow, 200);
        };

        function hideResultsNow() {
            var wasVisible = select.visible();
            select.hide();
            clearTimeout(timeout);
            stopLoading();
            if (options.mustMatch) {
                // call search and run callback
                $input.search(
				function(result) {
				    // if no value found, clear the input box
				    if (!result) {
				        if (options.multiple) {
				            var words = trimWords($input.val()).slice(0, -1);
				            $input.val(words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : ""));
				        }
				        else
				            $input.val("");
				    }
				}
			);
            }
            if (wasVisible)
            // position cursor at end of input field
                $.Autocompleter.Selection(input, input.value.length, input.value.length);
        };

        function receiveData(q, data) {
            if (data && data.length && hasFocus) {
                stopLoading();
                select.display(data, q);
                autoFill(q, data[0].value);
                select.show();
            } else {
                hideResultsNow();
            }
        };

        function request(term, success, failure) {
            if (!options.matchCase)
                term = term.toLowerCase();
            var data = cache.load(term);
            // recieve the cached data
            if (data && data.length) {
                success(term, data);
                // if an AJAX url has been supplied, try loading the data now
            } else if ((typeof options.url == "string") && (options.url.length > 0)) {

                var extraParams = {
                    timestamp: +new Date()
                };
                $.each(options.extraParams, function(key, param) {
                    extraParams[key] = typeof param == "function" ? param() : param;
                });

                $.ajax({
                    // try to leverage ajaxQueue plugin to abort previous requests
                    mode: "abort",
                    // limit abortion to this input
                    port: "autocomplete" + input.name,
                    dataType: options.dataType,
                    url: options.url,
                    data: $.extend({
                        q: lastWord(term),
                        limit: options.max
                    }, extraParams),
                    success: function(data) {
                        var parsed = options.parse && options.parse(data) || parse(data);
                        parsed.reverse();
                        cache.add(term, parsed);
                        success(term, parsed);
                    }
                });
            } else {
                // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
                select.emptyList();
                failure(term);
            }
        };

        function parse(data) {
            var parsed = [];
            var rows = data.split("\n");
            for (var i = 0; i < rows.length; i++) {
                var row = $.trim(rows[i]);
                if (row) {
                    row = row.split("|");
                    parsed[parsed.length] = {
                        data: row,
                        value: row[0],
                        result: options.formatResult && options.formatResult(row, row[0]) || row[0]
                    };
                }
            }
            return parsed;
        };

        function stopLoading() {
            $input.removeClass(options.loadingClass);
        };

    };

    $.Autocompleter.defaults = {
        inputClass: "ac_input",
        resultsClass: "ac_results",
        loadingClass: "ac_loading",
        minChars: 1,
        delay: 400,
        matchCase: false,
        matchSubset: true,
        matchContains: false,
        cacheLength: 10,
        max: 200,
        mustMatch: false,
        extraParams: {},
        selectFirst: true,
        formatItem: function(row) { return row[0]; },
        formatMatch: null,
        autoFill: false,
        width: 0,
        multiple: false,
        multipleSeparator: ";",
        highlight: function(value, term) {
            return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
        },
        scroll: true,
        scrollHeight: 180
    };

    $.Autocompleter.Cache = function(options) {

        var data = {};
        var length = 0;

        function matchSubset(s, sub) {
            if (!options.matchCase)
                s = s.toLowerCase();
            var i = s.indexOf(sub);
            if (i == -1) return false;
            return i == 0 || options.matchContains;
        };

        function add(q, value) {
            if (length > options.cacheLength) {
                flush();
            }
            if (!data[q]) {
                length++;
            }
            data[q] = value;
        }

        function populate() {
            if (!options.data) return false;
            // track the matches
            var stMatchSets = {},
			nullData = 0;

            // no url was specified, we need to adjust the cache length to make sure it fits the local data store
            if (!options.url) options.cacheLength = 1;

            // track all options for minChars = 0
            stMatchSets[""] = [];

            // loop through the array and create a lookup structure
            for (var i = 0, ol = options.data.length; i < ol; i++) {
                var rawValue = options.data[i];
                // if rawValue is a string, make an array otherwise just reference the array
                rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

                var value = options.formatMatch(rawValue, i + 1, options.data.length);
                if (value === false)
                    continue;

                var firstChar = value.charAt(0).toLowerCase();
                // if no lookup array for this character exists, look it up now
                if (!stMatchSets[firstChar])
                    stMatchSets[firstChar] = [];

                // if the match is a string
                var row = {
                    value: value,
                    data: rawValue,
                    result: options.formatResult && options.formatResult(rawValue) || value
                };

                // push the current match into the set list
                stMatchSets[firstChar].push(row);

                // keep track of minChars zero items
                if (nullData++ < options.max) {
                    stMatchSets[""].push(row);
                }
            };

            // add the data items to the cache
            $.each(stMatchSets, function(i, value) {
                // increase the cache size
                options.cacheLength++;
                // add to the cache
                add(i, value);
            });
        }

        // populate any existing data
        setTimeout(populate, 25);

        function flush() {
            data = {};
            length = 0;
        }

        return {
            flush: flush,
            add: add,
            populate: populate,
            load: function(q) {
                if (!options.cacheLength || !length)
                    return null;
                /* 
                * if dealing w/local data and matchContains than we must make sure
                * to loop through all the data collections looking for matches
                */
                if (!options.url && options.matchContains) {
                    // track all matches
                    var csub = [];
                    // loop through all the data grids for matches
                    for (var k in data) {
                        // don't search through the stMatchSets[""] (minChars: 0) cache
                        // this prevents duplicates
                        if (k.length > 0) {
                            var c = data[k];
                            $.each(c, function(i, x) {
                                // if we've got a match, add it to the array
                                if (matchSubset(x.value, q)) {
                                    csub.unshift(x);
                                }
                            });
                        }
                    }
                    return csub;
                } else
                // if the exact item exists, use it
                    if (data[q]) {
                    return data[q];
                } else
                    if (options.matchSubset) {
                    for (var i = q.length - 1; i >= options.minChars; i--) {
                        var c = data[q.substr(0, i)];
                        if (c) {
                            var csub = [];
                            $.each(c, function(i, x) {
                                if (matchSubset(x.value, q)) {
                                    csub.unshift(x);
                                }
                            });
                            return csub;
                        }
                    }
                }
                return null;
            }
        };
    };

    $.Autocompleter.Select = function(options, input, select, config) {
        var CLASSES = {
            ACTIVE: "ac_over"
        };

        var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list;

        // Create results
        function init() {
            if (!needsInit)
                return;
            element = $("<div/>")
		.hide()
		.addClass(options.resultsClass)
		.css("position", "absolute")
		.appendTo(document.body);

            list = $("<ul/>").appendTo(element).mouseover(function(event) {
                if (target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
                    active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
                    $(target(event)).addClass(CLASSES.ACTIVE);
                }
            }).click(function(event) {
                $(target(event)).addClass(CLASSES.ACTIVE);
                select();
                // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
                //input.focus();
                return false;
            }).mousedown(function() {
                config.mouseDownOnSelect = true;
            }).mouseup(function() {
                config.mouseDownOnSelect = false;
            });

            if (options.width > 0)
                element.css("width", options.width);

            needsInit = false;
        }

        function target(event) {
            var element = event.target;
            while (element && element.tagName != "LI")
                element = element.parentNode;
            // more fun with IE, sometimes event.target is empty, just ignore it then
            if (!element)
                return [];
            return element;
        }

        function moveSelect(step) {
            listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
            movePosition(step);
            var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
            if (options.scroll) {
                var offset = 0;
                listItems.slice(0, active).each(function() {
                    offset += this.offsetHeight;
                });
                if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                    list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
                } else if (offset < list.scrollTop()) {
                    list.scrollTop(offset);
                }
            }
        };

        function movePosition(step) {
            active += step;
            if (active < 0) {
                active = listItems.size() - 1;
            } else if (active >= listItems.size()) {
                active = 0;
            }
        }

        function limitNumberOfItems(available) {
            return options.max && options.max < available
			? options.max
			: available;
        }

        function fillList() {
            list.empty();
            var max = limitNumberOfItems(data.length);
            for (var i = max - 1; i >= 0; i--) {
                if (!data[i])
                    continue;
                var formatted = options.formatItem(data[i].data, i + 1, max, data[i].value, term);
                if (formatted === false)
                    continue;
                var li = $("<li/>").html(options.highlight(formatted, term)).addClass(i % 2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
                $.data(li, "ac_data", data[i]);
            }
            listItems = list.find("li");
            if (options.selectFirst) {
                listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
                active = 0;
            }
            // apply bgiframe if available
            if ($.fn.bgiframe)
                list.bgiframe();
        }

        return {
            display: function(d, q) {
                init();
                data = d;
                term = q;
                fillList();
            },
            next: function() {
                moveSelect(1);
            },
            prev: function() {
                moveSelect(-1);
            },
            pageUp: function() {
                if (active != 0 && active - 8 < 0) {
                    moveSelect(-active);
                } else {
                    moveSelect(-8);
                }
            },
            pageDown: function() {
                if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
                    moveSelect(listItems.size() - 1 - active);
                } else {
                    moveSelect(8);
                }
            },
            hide: function() {
                element && element.hide();
                listItems && listItems.removeClass(CLASSES.ACTIVE);
                active = -1;
            },
            visible: function() {
                return element && element.is(":visible");
            },
            current: function() {
                return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
            },
            show: function() {
                var offset = $(input).offset();
                element.css({
                    width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
                    top: offset.top + input.offsetHeight,
                    left: offset.left
                }).show();
                if (options.scroll) {
                    list.scrollTop(0);
                    if (listItems.length >= 9) {
                        list.css({
                            height: options.scrollHeight + 'px',
                            overflow: 'auto'
                        });
                    }
                    else {
                        list.css({
                            height: 'auto',
                            overflow: 'auto'
                        });
                    }

                    if ($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
                        var listHeight = 0;
                        listItems.each(function() {
                            listHeight += this.offsetHeight;
                        });
                        var scrollbarsVisible = listHeight > options.scrollHeight;
                        list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight);
                        if (!scrollbarsVisible) {
                            // IE doesn't recalculate width when scrollbar disappears
                            listItems.width(list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")));
                        }
                    }

                }
            },
            selected: function() {
                var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
                return selected && selected.length && $.data(selected[0], "ac_data");
            },
            emptyList: function() {
                list && list.empty();
            },
            unbind: function() {
                element && element.remove();
            }
        };
    };

    $.Autocompleter.Selection = function(field, start, end) {
        if (field.createTextRange) {
            var selRange = field.createTextRange();
            selRange.collapse(true);
            selRange.moveStart("character", start);
            selRange.moveEnd("character", end);
            selRange.select();
        } else if (field.setSelectionRange) {
            field.setSelectionRange(start, end);
        } else {
            if (field.selectionStart) {
                field.selectionStart = start;
                field.selectionEnd = end;
            }
        }
        field.focus();
    };

})(jQuery);

//td tips by bestshuai
(function($) {
    $.fn.autotips = function() {
        return this.each(function() {
            var obj = $(this);
            if (!$(document).attr('tipsInited')) {
                $(document.body).append($("<div id='autotipsdiv' style='position:absolute;display:none;word-wrap:break-word;word-break:break-all;background-color:white;border:solid 1px blue;padding:2px;'></div>"));
                $(document).attr('tipsInited', 'true');
                var div = $('#autotipsdiv');
                $(div).hover(function() { }, function() {
                    $(this).css('display', 'none');
                    //if ($.browser.msie && $.browser.version <= '6.0') {
                    $(this).html('');
                    $(this).css('width', 'auto');
                    //}
                });
            }
            obj.find("TD").each(function() {
                if (!$(this).attr('tipsInited')) {
                    $(this).attr('tipsInited', 'true');
                    if ($(this).attr('class').indexOf('noautotips') >= 0)
                        return;
                    $(this).hover(function() {
                        var div = $('#autotipsdiv');
                        div.html('');
                        div.css('width', 'auto');
                        div.css('line-height', $(this).height() + 'px');
                        div.css('left', $(this).offset().left + 'px');
                        div.css('top', $(this).offset().top + 'px');
                        //div.css('min-height', $(this).height() + 'px');
                        //div.css('min-width', $(this).width() + 'px');
                        var maxWidth = $(this).parent().attr('offsetWidth') - $(this).attr('offsetLeft');
                        if (maxWidth < $(this).attr('offsetWidth'))
                            maxWidth = $(this).attr('offsetWidth');
                        //div.css('max-width', maxWidth + 'px');
                        if ($(this).css('text-align')) {
                            div.css('text-align', $(this).css('text-align'));
                        }
                        else if ($(this).attr('align')) {
                            div.css('text-align', $(this).attr('align'));
                        }
                        else {
                            div.css('text-align', 'left');
                        }
                        div.html($(this).html());
                        div.css('display', '');
                        if (div.attr('offsetWidth') < $(this).attr('offsetWidth'))
                            div.css('display', 'none');
                        else {
                            //if ($.browser.msie && $.browser.version <= '6.0') {
                            var ie6width = div.attr('offsetWidth') < $(this).attr('offsetWidth') ? $(this).attr('offsetWidth') +
                            "px" : (div.attr('offsetWidth') > maxWidth ? maxWidth + "px" : "auto");
                            div.css("width", ie6width);
                        }
                        //}
                    }, function() { });
                }
            });
        });
    };
})(jQuery);

//userChooser deptChooser by bestshuai
(function($) {
    $.fn.userChooser = function(includeDimission) {
        if (this.attr('userchooserinited') == 'true') return;
        this.attr('userchooserinited', 'true');
        var multiple = '' + this.attr('multiple');
        multiple = multiple ? multiple.toLowerCase() : false;
        this.autocomplete("../StaffFilter.aspx?includeDimission=" + includeDimission,
        {
            delay: 200,
            minChars: 1,
            matchSubset: 1,
            matchContains: 1,
            cacheLength: 10,
            multipleSeparator: ';',
            multiple: multiple == 'true',
            mustMatch: true,
            dataType: 'json',
            parse: function(data) {
                var rows = new Array();
                for (var i = 0; i < data.length; i++) {
                    rows[i] = { data: data[i], value: data[i].ID.toString(), result: data[i].Name };
                }
                return rows;
            },
            formatItem: function(row, i, max, value, term) {
                return row.Name;
            },
            scroll: false
        });
        this.result(function() { if (multiple == 'true') { this.focus(); $(this).endInsPoint(); } else this.blur(); });
        this.focus(function() { if (multiple == 'true') { $(this).endInsPoint(); } else this.select(); });
    };

    $.fn.deptChooser = function(level) {
        if (this.attr('deptchooserinited') == 'true') return;
        this.attr('deptchooserinited', 'true');
        var multiple = '' + this.attr('multiple');
        multiple = multiple ? multiple.toLowerCase() : false;
        if (!level) level = 2;
        this.autocomplete("../DeptFilter.aspx?level=" + level,
        {
            delay: 200,
            minChars: 1,
            matchSubset: 1,
            matchContains: 1,
            cacheLength: 10,
            multipleSeparator: ';',
            multiple: multiple == 'true',
            mustMatch: true,
            dataType: 'json',
            parse: function(data) {
                var rows = new Array();
                for (var i = 0; i < data.length; i++) {
                    rows[i] = { data: data[i], value: data[i].ID.toString(), result: data[i].Name };
                }
                return rows;
            },
            formatItem: function(row, i, max, value, term) {
                return row.Name;
            },
            scroll: false
        });
        this.result(function() { if (multiple == 'true') { this.focus(); $(this).endInsPoint(); } else this.blur(); });
        this.focus(function() { if (multiple == 'true') { $(this).endInsPoint(); } else this.select(); });
    };

    $.fn.customerChooser = function(onselectchange) {
        if (this.attr('customerchooserinited') == 'true') this.unautocomplete();
        this.attr('customerchooserinited', 'true');
        var multiple = '' + this.attr('multiple');
        multiple = multiple ? multiple.toLowerCase() : false;
        var ouid = this.attr('ouid');
        if (ouid == undefined) return;
        var showcustomeraddress = 0;
        if (this.attr('showcustomeraddress') != undefined) {
            showcustomeraddress = this.attr('showcustomeraddress');
        }
        this.autocomplete("../CustomerFilter.aspx?ouid=" + ouid + "&showcustomeraddress=" + showcustomeraddress,
        {
            delay: 200,
            minChars: 1,
            matchSubset: 1,
            matchContains: 1,
            cacheLength: 10,
            multipleSeparator: ';',
            multiple: multiple == 'true',
            mustMatch: true,
            dataType: 'json',
            parse: function(data) {
                var rows = new Array();
                for (var i = 0; i < data.length; i++) {
                    rows[i] = { data: data[i], value: data[i].ID.toString(), result: data[i].Name };
                }
                return rows;
            },
            formatItem: function(row, i, max, value, term) {
                return row.Name;
            },
            scroll: false
        });
        this.result(
            function() {
                showNorepeat();
                if (multiple == 'true') { this.focus(); $(this).endInsPoint(); } else { this.blur(); }
                var mycustomersel = this;
                if (showcustomeraddress == 0) {
                    var customername = this.value;
                    $.getJSON("/IMSv3/c/DictControl/GetCustomerDetailsByNameAndOuId/?__exp=0", { pOuId: ouid, pName: customername },
                        function(data) {
                            mycustomersel.customerid = data[0]["CustomerId"];
                            mycustomersel.customername = data[0]["CustomerName"];
                            mycustomersel.regionid = data[0]["RegionId"];
                            mycustomersel.regionname = data[0]["RegionName"];
                            mycustomersel.provinceid = data[0]["ProvinceId"];
                            mycustomersel.provincename = data[0]["ProvinceName"];
                            mycustomersel.addressid = data[0]["AddressId"];
                            mycustomersel.addressname = data[0]["AddressName"];
                            if (typeof (onselectchange) == 'function') { onselectchange(); }
                            hideNorepeat();
                        }
                    );
                }
                else {
                    var indexTemp = this.value.indexOf('|');
                    var customername = this.value.substring(0, indexTemp);
                    var addressname = this.value.substring(indexTemp + 1);
                    $.getJSON("/IMSv3/c/DictControl/GetCustomerDetailsByAddressName/?__exp=0", { pOuId: ouid, pName: customername, pAddressName: addressname },
                        function(data) {
                            mycustomersel.customerid = data[0]["CustomerId"];
                            mycustomersel.customername = data[0]["CustomerName"];
                            mycustomersel.regionid = data[0]["RegionId"];
                            mycustomersel.regionname = data[0]["RegionName"];
                            mycustomersel.provinceid = data[0]["ProvinceId"];
                            mycustomersel.provincename = data[0]["ProvinceName"];
                            mycustomersel.addressid = data[0]["AddressId"];
                            mycustomersel.addressname = data[0]["AddressName"];
                            if (typeof (onselectchange) == 'function') { onselectchange(); }
                            hideNorepeat();
                        }
                    );
                }
            }
        );
        this.focus(function() { if (multiple == 'true') { $(this).endInsPoint(); } else this.select(); });
    };

    $.fn.getValSelected = function() {
        var data = this.data('data');
        var text_prop = this.data('text_prop');
        var val_prop = this.data('val_prop');
        function findval(text) {
            for (var i = 0; i < data.length; i++) {
                if ($(data[i]).attr(text_prop) == text) {
                    return $(data[i]).attr(val_prop);
                }
            }
            return null;
        }
        var val = this.val();
        var txtsels = val.split(';');
        var valsels = [];
        for (var i = 0; i < txtsels.length; i++) {
            if (txtsels[i] == '') continue;
            var tmp = findval(txtsels[i]);
            if (tmp == null) continue;
            valsels[valsels.length] = tmp;
        }
        return valsels.join(';');
    };
    $.fn.dataChooser = function(data, text_prop, val_prop, onselectchange, mustmatch) {
        if (mustmatch == null)
            mustmatch = true;
        if (!text_prop)
            text_prop = 'Value';
        if (!val_prop)
            val_prop = 'Key';
        var multiple = '' + this.attr('multiple');
        multiple = multiple ? multiple.toLowerCase() : false;
        this.unautocomplete();
        this.autocomplete(data, {
            delay: 100,
            minChars: 1,
            matchSubset: 1,
            matchContains: 1,
            cacheLength: 10,
            multipleSeparator: ';',
            multiple: multiple == 'true',
            mustMatch: mustmatch,
            dataType: 'json',
            parse: function(data) {
                return data;
            },
            formatItem: function(row, i, max, value, term) {
                return $(row).attr(text_prop);
            },
            scroll: true
        });
        this.data('data', data);
        this.data('text_prop', text_prop);
        this.data('val_prop', val_prop);
        this.result(function() {
            if (multiple == 'true') {
                this.focus();
                $(this).endInsPoint();
            } else
                this.blur();
            if (onselectchange)
                onselectchange();
        });
        this.focus(function() {
            var oThis = $(this);
            if (multiple == 'true') {
                setTimeout(function() {
                    oThis.endInsPoint();
                }, 50);
            } else
                this.select();
        });
        return this;
    };
})(jQuery);

(function($) {
    var m = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"': '\\"',
        '\\': '\\\\'
    },
        s = {
            'array': function(x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function(x) {
                return String(x);
            },
            'null': function(x) {
                return "null";
            },
            'number': function(x) {
                if (x instanceof Array) {
                    return s.array(x);
                }
                if (isDateObject(x)) {
                    var tick = x - 0;
                    var str = String(x);
                    var timezone = str.match(/[\+-][0-9]{4}/);
                    return '"\/Date(' + tick + '' + (timezone.length > 0 ? timezone[0] : '') + ')\/"';
                }
                else {
                    return isFinite(x) ? String(x) : 'null';
                }
            },
            'object': function(x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            'string': function(x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

    $.toJSON = function(v) {
        var f = isNaN(v) ? s[typeof v] : s['number'];
        if (f) return f(v);
    };

    $.parseJSON = function(v, safe) {
        if (safe === undefined) safe = $.parseJSON.safe;
        if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
            return undefined;
        var re = eval('(' + v + ')');
        //Date
        var rem = v.match(/^\/Date\(([0-9]{1,})[\+-][0-9]{4}\)/);
        if (rem && rem.length == 2) {
            return new Date(parseInt(rem[1], 10));
        }
        if ((typeof re) == "string") {
            rem = re.match(/^\/Date\(([0-9]{1,})[\+-][0-9]{4}\)/);
            if (rem && rem.length == 2) {
                return new Date(parseInt(rem[1], 10));
            }
        }
        return re;
    };

    $.parseJSON.safe = false;

})(jQuery);

//fileUploader
(function($) {
    $.fn.doUpload = function() {
        $(this).find('input.upload').click();
    };
    $.fn.fileUpload = function(virtualDicionary, appID, oncomplete, nameprefixlist) {
        if ($.trim($(this).html()) != '')
            return;
        var updiv = $("<div class='panel' style='width:100%'>" +
                    "<input type='button' class='add' disabled value='添加文件' />" +
                    "<input class='upload' type='button' disabled  value='上传' />" +
                    "<input class='cancel' type='button' disabled value='取消' />" +
                    "<div class='framediv' style='width:100%;'></div>" +
                    "<div class='progress' style='width:100%;display:none;'></div>" +
                    "</div>");
        var progressdiv = $("<div>" +
				"<span></span><br/>" +
				"总体进度:" +
				"<div style='BORDER-RIGHT:blue 1px solid; BORDER-TOP:blue 1px solid; BORDER-LEFT:blue 1px solid; WIDTH:500px; BORDER-BOTTOM:blue 1px solid; HEIGHT:30px'>" +
					"<div class='bar' style='HEIGHT:100%;BACKGROUND-COLOR:green'></div>" +
				"</div>" +
			    "</div>");
        updiv.appendTo($(this));
        var uploadUrl = '';
        var uploadId = '';
        var info = progressdiv.find('span');
        var bar = progressdiv.find('.bar');
        var addbtn = updiv.find('.add');
        var uploadbtn = updiv.find('.upload');
        var cancelbtn = updiv.find('.cancel');
        var framediv = updiv.find('.framediv');
        var upframe;
        var framebody;
        var frameform;
        var progress = updiv.find('.progress');
        function getProgress(uploadId) {
            $.getJSON(virtualDicionary + 'c/GasClient/GetProgress/?__exp=0&uploadId=' + uploadId,
            function(data) {
                if (data == null || data == "") {
                    setTimeout(function() { getProgress(uploadId); }, 1000);
                    return;
                }
                var len = data.ContentLength;
                var lenstr = data.ContentLengthString;
                var curfile = data.CurrentFileName;
                var speed = data.Speed;
                var speedstr = data.SpeedString;
                var pos = data.Position;
                var posstr = data.PositionString;
                var error = data.ErrorMessage;
                var state = data.State;
                var reason = data.Reason;
                if (state == 0)//completed
                {
                    upframe.css('display', '');
                    upframe.height('0px');
                    initupload();
                    progress.text('上传完成');
                    if (oncomplete)
                        oncomplete(data);
                    progress.text('');
                }
                else if (state == 2)//terminated
                {
                    upframe.css('display', '');
                    upframe.height('0px');
                    initupload();
                    progress.text('上传中断, 原因: ' + reason);
                }
                else {
                    info.text('当前文件: ' + curfile + ', 速度: ' + speedstr + ', 已上传' + posstr);
                    bar.width((pos * 100 / len) + '%');
                    progress.html(progressdiv.html());
                    setTimeout(function() { getProgress(uploadId); }, 600);
                }
            });
        }
        addbtn.bind('click.add', function() {
            var len = frameform.find('input').length;
            //ie中，append必须是frame内的doc创建的, so只能这样
            if (nameprefixlist) {
                frameform.append('<div id=' + len + '><select name="fn"></select>&nbsp;&nbsp;<input name="' + len + '" id="' + len + '" type="file"></input><a href="#" style="font-size:10pt;">删除</a></div>');
                var select = frameform.find('#' + len + ' select');
                $(nameprefixlist).each(function(index, data) { select.append('<option value="' + data + '">' + data + '</option>'); });
            }
            else {
                frameform.append('&nbsp;&nbsp;<div id=' + len + '><input name="' + len + '" id="' + len + '" type="file"></input><a href="#" style="font-size:10pt;">删除</a></div>');
            }
            var line = frameform.find('#' + len);
            var btn = frameform.find('#' + len + ' a');
            var filebtn = frameform.find('#' + len + ' input');
            btn.bind('click.removeline', function() {
                line.remove();
                if (frameform.find('input[type=file]').length == 0)
                { upframe.height('0px'); }
                else
                { upframe.height(framebody.attr('scrollHeight') + 'px'); }
                return false;
            });
            upframe.height(framebody.attr('scrollHeight') + 'px');
        });
        uploadbtn.bind('click.upload', function() {
            var hasFile = false;
            frameform.find('input').each(function() {
                if ($(this).val() != '')
                    hasFile = true;
            });
            if (!hasFile) {
                alert('请至少选择一个文件！');
                return;
            }
            progress.show();
            //移除事件，以免在IE中因为提交后jquery清理事件时由于跨域而报错
            frameform.find('a').each(function() { $(this).unbind("click.removeline"); });
            frameform.submit();
            upframe.css('display', 'none');
            addbtn.attr('disabled', 'true');
            uploadbtn.attr('disabled', 'true');
            cancelbtn.attr('disabled', '');
            progress.text('开始上传......');
            setTimeout(function() { getProgress(uploadId); }, 1000);
        });
        cancelbtn.bind('click.cancel', function() { });
        function initupload() {
            $.getJSON(virtualDicionary + 'c/GasClient/GetUploadUrl/?__exp=0&appID=' + appID, function(data) {
                uploadUrl = data;
                uploadId = data.substr(data.indexOf('uploadId=') + 9);
                if (upframe) upframe.remove();
                upframe = $("<iframe frameborder='0' scrolling='no' height='0'></iframe>");
                framediv.append(upframe);
                upframe.css('width', 480 + 'px');
                upframe.bind('load.initupload', function() {
                    framebody = upframe.contents().find('body');
                    framebody.css('marginLeft', '2px');
                    framebody.css('marginTop', '2px');
                    framebody.css('marginBottom', '0px');
                    framebody.css('marginRight', '0px');
                    framebody.append("<form method='POST' name='uploadForm' style='margin:0px 0px 0px 0px;' enctype='multipart/form-data'></form>");
                    frameform = framebody.find('form');
                    frameform.attr('action', uploadUrl);
                    upframe.unbind('load.initupload');
                });

                addbtn.attr('disabled', '');
                uploadbtn.attr('disabled', '');
                cancelbtn.attr('disabled', 'true');
                cancelbtn.hide();

            });
        }
        initupload();
    };
})(jQuery);
(function($) {
    $.fn.getCount = function() {
        var frameDiv = $(this).find('.framediv');
        var upframe = frameDiv.find('iframe');
        var framebody = upframe.contents().find('body')
        var frameform = framebody.find('form');

        var count = 0;
        frameform.find('input').each(function() {
            if ($(this).val() != '')
                count++;
        });
        if (count == 0) {
            //alert('请至少选择一个文件！');
            return 0;
        }
        return count;
    };
})(jQuery);

(function($) {
    $.fn.getCount = function() {
        var frameDiv = $(this).find('.framediv');
        var upframe = frameDiv.find('iframe');
        var framebody = upframe.contents().find('body')
        var frameform = framebody.find('form');

        var count = 0;
        frameform.find('input').each(function() {
            if ($(this).val() != '')
                count++;
        });
        if (count == 0) {
            //alert('请至少选择一个文件！');
            return 0;
        }
        return count;
    };
})(jQuery);

(function($) {
    $.fn.addDropdownButton = function(q) {
        var oThis = this;
        if (this.attr('initedadddropdownbutton') == 'true') return;
        this.attr('initedadddropdownbutton', 'true');
        this.unbind('click.dropdown');
        if (!q) q = '';
        this.bind('click.dropdown', function() { oThis.showList(q); });
        this.css('cursor', 'default');
        this.focus(function() { $(this).css('cursor', ''); });
        this.blur(function() { $(this).css('cursor', 'default'); });
        this.css('border', '1px solid #BBBBBB');
        this.css('width', this.width() + 2);
        this.css('background', '#FFFFFF url(../../content/images/dropdown.gif) no-repeat scroll right center');
        this.mouseover(function() { $(this).css('background-image', "url(../../content/images/dropdown_hover.gif)"); });
        this.mouseout(function() { $(this).css('background-image', "url(../../content/images/dropdown.gif)"); });
    }
})(jQuery);

/**
* linkbutton 1.0 - jQuery Plug-in
* 
* Licensed under the GPL:
*   http://gplv3.fsf.org
*
* Copyright 2009 stworthy [ stworthy@gmail.com ] 
*/
(function($) {
    $.fn.linkbutton = function(options) {

        // wrap the link button, make sure to execute once
        function wrapButton(target) {
            $(target).addClass('l-btn');

            if ($.trim($(target).html().replace(/&nbsp;/g, ' ')) == '') {
                $(target).html('&nbsp;').wrapInner(
						'<span class="l-btn-left">' +
						'<span class="l-btn-text">' +
						'<span class="l-btn-empty"></span>' +
						'</span>' +
						'</span>'
				);

                var iconCls = $(target).attr('icon');
                if (iconCls) {
                    $('.l-btn-empty', target).addClass(iconCls);
                }
            } else {
                $(target).wrapInner(
						'<span class="l-btn-left">' +
						'<span class="l-btn-text">' +
						'</span>' +
						'</span>'
				);

                var cc = $('.l-btn-text', target);
                var iconCls = $(target).attr('icon');
                if (iconCls) {
                    cc.addClass(iconCls).css('padding-left', '20px');
                }
                if (/^[u4E00-u9FA5]/.test(cc.text()) == false && $.browser.msie) {
                    cc.css('padding-top', '2px');
                }
            }
        }

        return this.each(function() {
            var opts;
            var state = $.data(this, 'linkbutton');
            if (state) {
                opts = $.extend(state.options, options || {});
                state.options = opts;
            } else {
                wrapButton(this);
                opts = $.extend({}, $.fn.linkbutton.defaults, options || {});

                if ($(this).hasClass('l-btn-plain')) {
                    opts.plain = true;
                }

                // the button initialize state is disabled
                if ($(this).attr('disabled')) {
                    opts.disabled = true;
                    $(this).removeAttr('disabled');
                }

                state = { options: opts };

            }

            if (state.options.disabled) {
                var href = $(this).attr('href');
                if (href) {
                    state.href = href;
                    $(this).removeAttr('href');
                }
                var onclick = $(this).attr('onclick');
                if (onclick) {
                    state.onclick = onclick;
                    $(this).attr('onclick', null);
                }
                $(this).addClass('l-btn-disabled');
            } else {
                if (state.href) {
                    $(this).attr('href', state.href);
                }
                if (state.onclick) {
                    this.onclick = state.onclick;
                }
                $(this).removeClass('l-btn-disabled');
            }

            if (state.options.plain == true) {
                $(this).addClass('l-btn-plain');
            } else {
                $(this).removeClass('l-btn-plain');
            }

            $.data(this, 'linkbutton', state); // save the button state
        });
    };

    $.fn.linkbutton.defaults = {
        disabled: false,
        plain: false
    };

    $(function() {
        $('a.l-btn').linkbutton();
    });
})(jQuery);
/**
* pagination 1.0 - jQuery Plug-in
* 
* Licensed under the GPL:
*   http://gplv3.fsf.org
*
* Copyright 2009 stworthy [ stworthy@gmail.com ] 
* 
* Dependencies:
* 	linkbutton
* 
*/
(function($) {
    $.fn.pagination = function(options) {

        if (typeof options == 'string') {
            switch (options) {
                case 'options':
                    return $.data(this[0], 'pagination').options;
            }
        }

        options = options || {};

        function contains(v, aa) {
            for (var i = 0; i < aa.length; i++) {
                if (aa[i] == v) return true;
            }
            return false;
        }

        return this.each(function() {
            var opts;
            var state = $.data(this, 'pagination');
            if (state) {
                opts = $.extend(state.options, options);
            } else {
                opts = $.extend({}, $.fn.pagination.defaults, options);
                if (!contains(opts.pageSize, opts.pageList)) {
                    opts.pageSize = opts.pageList[0];
                }
                $.data(this, 'pagination', {
                    options: opts
                });
            }

            var total = opts.total;
            var pageNumber = opts.pageNumber;
            var pageSize = opts.pageSize;
            var pageCount = Math.ceil(total / pageSize);

            var pager = $(this);
            render();

            function selectPage(page) {
                return function() {
                    pageNumber = page;
                    if (pageNumber < 1) pageNumber = 1;
                    if (pageNumber > pageCount) pageNumber = pageCount;

                    opts.pageNumber = pageNumber; // save the pageNumber state
                    opts.pageSize = pageSize;
                    opts.onSelectPage.call(pager, pageNumber, pageSize);

                    render();
                };
            }

            function render() {
                pager.addClass('pagination').empty();
                var t = $('<table cellspacing="0" cellpadding="0" border="0"><tr></tr></table>').appendTo(pager);
                var tr = $('tr', t);

                var ps = $('<select class="pagination-page-list"></select>');
                for (var i = 0; i < opts.pageList.length; i++) {
                    $('<option></option>')
							.text(opts.pageList[i])
							.attr('selected', opts.pageList[i] == pageSize ? 'selected' : '')
							.appendTo(ps);
                }
                $('<td></td>').append(ps).appendTo(tr);

                $('<td><div class="pagination-btn-separator"></div></td>').appendTo(tr);
                $('<td><a icon="pagination-first"></a></td>').appendTo(tr);
                $('<td><a icon="pagination-prev"></a></td>').appendTo(tr);
                $('<td><div class="pagination-btn-separator"></div></td>').appendTo(tr);

                $('<span style="padding-left:6px;"></span>')
						.html(opts.beforePageText)
						.wrap('<td></td>')
						.parent().appendTo(tr);
                $('<td><input class="pagination-num" type="text" value="1" size="2" /></td>').appendTo(tr);
                $('<span style="padding-right:6px;"></span>')
						.html(opts.afterPageText.replace(/{pages}/, pageCount))
						.wrap('<td></td>')
						.parent().appendTo(tr);

                $('<td><div class="pagination-btn-separator"></div></td>').appendTo(tr);
                $('<td><a icon="pagination-next"></a></td>').appendTo(tr);
                $('<td><a icon="pagination-last"></a></td>').appendTo(tr);
                $('<td><div class="pagination-btn-separator"></div></td>').appendTo(tr);

                if (opts.loading) {
                    $('<td><a icon="pagination-loading"></a></td>').appendTo(tr);
                } else {
                    $('<td><a icon="pagination-load"></a></td>').appendTo(tr);
                }

                if (opts.buttons) {
                    $('<td><div class="pagination-btn-separator"></div></td>').appendTo(tr);
                    for (var i = 0; i < opts.buttons.length; i++) {
                        var btn = opts.buttons[i];
                        if (btn == '-') {
                            $('<td><div class="pagination-btn-separator"></div></td>').appendTo(tr);
                        } else {
                            var td = $('<td></td>').appendTo(tr);
                            $('<a href="javascript:void(0)"></a>')
									.addClass('l-btn')
									.css('float', 'left')
									.text(btn.text || '')
									.attr('icon', btn.iconCls || '')
									.bind('click', eval(btn.handler || function() { }))
									.appendTo(td)
									.linkbutton({ plain: true });
                        }
                    }
                }

                var pinfo = opts.displayMsg;
                pinfo = pinfo.replace(/{from}/, pageSize * (pageNumber - 1) + 1);
                pinfo = pinfo.replace(/{to}/, Math.min(pageSize * (pageNumber), total));
                pinfo = pinfo.replace(/{total}/, total);
                $('<div class="pagination-info"></div>')
						.html(opts.displayMsg)
						.html(pinfo)
						.appendTo(pager);

                //$('<div style="clear:both; height: 0px;"></div>').appendTo(pager);

                $('a', pager).attr('href', 'javascript:void(0)').linkbutton({ plain: true });

                $('a[icon=pagination-first]', pager).bind('click', selectPage(1));
                $('a[icon=pagination-prev]', pager).bind('click', selectPage(pageNumber - 1));
                $('a[icon=pagination-next]', pager).bind('click', selectPage(pageNumber + 1));
                $('a[icon=pagination-last]', pager).bind('click', selectPage(pageCount));
                $('a[icon=pagination-load]', pager).bind('click', selectPage(pageNumber));
                $('a[icon=pagination-loading]', pager).bind('click', selectPage(pageNumber));
                if (pageNumber == 1) {
                    $('a[icon=pagination-first],a[icon=pagination-prev]', pager)
							.unbind('click')
							.linkbutton({ disabled: true });
                }
                if (pageNumber == pageCount) {
                    $('a[icon=pagination-last],a[icon=pagination-next]', pager)
							.unbind('click')
							.linkbutton({ disabled: true });
                }

                $('input.pagination-num', pager)
						.val(pageNumber)
						.keydown(function(e) {
						    if (e.keyCode == 13) {
						        pageNumber = parseInt($(this).val(), 10) || 1;
						        selectPage(pageNumber)();
						    }
						});
                $('.pagination-page-list', pager).change(function() {
                    pageSize = $(this).val();
                    pageCount = Math.ceil(total / pageSize);
                    pageNumber = opts.pageNumber;
                    selectPage(pageNumber)();
                });
            }
        });
    };

    $.fn.pagination.defaults = {
        total: 1,
        pageSize: 10,
        pageNumber: 1,
        pageList: [5, 10, 20, 30, 50],
        loading: false,
        buttons: null,
        onSelectPage: function(pageNumber, pageSize) { },

        beforePageText: '第',
        afterPageText: '总计{pages}页',
        displayMsg: ' {from}-{to} 总计{total}条'
    };
})(jQuery);


/**tab**/
(function($) {
    $.fn.tab = function(json, func, defaultType) {
        this.attr('func', func);
        var h = '<ul>';
        var pager = $(this);
        var dt = defaultType;
        pager.append('<ul></ul>');
        $(json).each(function(index, item) {
            h += "<li><a><span>" + item.Text + "</span></a></li>";
        });
        h += "</ul>";
        pager.append(h);
        $(json).each(function(index, item) {
            var obj = pager[0].children[1].children[index].children[0];
            $(obj).bind('click', onTabChange(item.Value));
            if (dt == item.Value) {
                var obj2 = pager[0].children[1].children[index];
                $(obj2).attr("class", "selected");
            }
        });

        function onTabChange(type) {
            return function() {
                $(json).each(function(index, item) {
                    if (type == item.Value) {
                        var obj = pager[0].children[1].children[index];
                        $(obj).attr("class", "selected");
                    }
                    else {
                        var obj = pager[0].children[1].children[index];
                        $(obj).attr("class", "");
                    }
                });
                if (typeof (eval(func)) == "function") {
                    try {
                        eval(func + '(type)');
                    }
                    catch (e)
	             	{ }
                }
            };
        }
    };
})(jQuery);

//高度自动适应
(function($) {
    $.fn.autoExpand = function() {
        var oThis = this;
        if (oThis.attr('isAutoExpandInited') == 'true')
            return;
        oThis.attr('isAutoExpandInited', 'true');
        oThis.css('overflow-y', 'hidden');
        oThis.keydown(function() {
            if (oThis.attr('scrollHeight') > 40) {
                setTimeout(function() {
                    oThis.css('height', oThis.attr('scrollHeight') + 'px');
                }, 50);
            }
        });
    }
})(jQuery);

(function($) {
    $.fn.litetabs = function(index) {
        var oThis = this;
        if (oThis.attr('islitetabsInited') == 'true')
            return;
        if (!index)
            index = 0;
        oThis.attr('islitetabsInited', 'true');
        var tabs = oThis.find('ul.tabs');
        var items = tabs.find('> li');
        items.each(function(curindex, item) {
            var link = $(item).find('a');
            var target = '#' + link.attr('key');
            if (curindex == index) {
                $(target).css('display', '');
                $(item).attr('className', 'selected');
            }
            else {
                $(target).css('display', 'none');
            }
            link.bind('click.litetabs', function() {
                var contents = oThis.find('.content').children();
                contents.each(function() {
                    $(this).css('display', 'none');
                });
                items = tabs.find('> li');
                items.each(function() { $(this).attr('className', ''); });
                link.parent().attr('className', 'selected');
                $(target).css('display', '');
                return false;
            });
        });
    }
})(jQuery);

; (function($) {
    $.fn.listAttachment = function(virtualDicionary, appID, isShowDelete) {
        if ($.trim($(this).html()) != '')
            return;
        var target = $(this);
        var gb = 1024 * 1024 * 1024;
        var mb = 1024 * 1024;
        var kb = 1024;
        function getSizeString(size) {
            if (size > gb)
                return Math.round((size / gb) * 100) / 100 + 'GB';
            if (size > mb)
                return Math.round((size / mb) * 100) / 100 + 'MB';
            if (size > kb)
                return Math.round((size / kb) * 100) / 100 + 'KB';
            return (size) + '字节';
        }
        var panel = $('<div class="attachment"></div>');
        $(this).append(panel);
        $.getJSON(virtualDicionary + 'c/GasClient/GetAttachments/?__exp=0&appID=' + appID, function(data) {
            if (data != "") {
                $(data).each(function() {
                    var item = $('<div></div>');
                    var dataitem = this;
                    panel.append(item);
                    item.append('<span class="name">' + dataitem.FileName + '</span>');
                    $.getJSON(virtualDicionary + 'c/GasClient/GetViewUrl,GetDownloadUrl/?__exp=0&appID=' + appID + '&attID=' + dataitem.Guid, function(data) {
                        var sizeinfo = $('<span class="size"></span>');
                        sizeinfo.text('(' + getSizeString(dataitem.Size) + ')');
                        item.append(sizeinfo);
                        //var viewlink = $('<a class="link" href="' + data[0] + '&noframe=true" target="_blank">预览</a>');
                        //item.append(viewlink);
                        var downlink = $('<a class="link" href="' + data[1] + '&noframe=true" target="_blank">下载</a>');
                        item.append(downlink);
                        if (isShowDelete) {
                            var dellink = $('<a class="link" href="#">删除</a>');
                            item.append(dellink);
                            dellink.click(function() {
                                if (!confirm('确定删除吗？')) return false;
                                $.get(virtualDicionary + 'c/GasClient/DeleteAttachments/?__exp=0&appID=' + appID + '&attID=' + dataitem.Guid, function() {
                                    target.html('');
                                    target.listAttachment(virtualDicionary, appID, isShowDelete);
                                });
                                return false;
                            });
                        }
                        item.css('cursor', 'pointer');
                        item.bind('click.attachment', function() {
                            var iframe = item.next('iframe');
                            if (iframe.length > 0) {
                                if (iframe.css('display') == 'none') {
                                    $('.previewiframe').hide();
                                    iframe.show();
                                }
                                else {
                                    iframe.hide();
                                }
                                return;
                            }
                            else {
                                $('.previewiframe').hide();
                            }
                            var frame = $('<iframe class="previewiframe" src="' + data[0]
                            + '" width="' + item.width() + '" height="500" frameborder=0 style="border:solid 1px gray;"></iframe>');
                            item.after(frame);
                        })
                    });
                });
            }
        });
    }
})(jQuery);

; (function($) {
    $.fn.listAttachmentFM = function(virtualDicionary, systemID, appID, isShowDelete, onlistcomplete) {
        if ($.trim(this.html()) != '')
            return;
        var target = this;
        var gb = 1024 * 1024 * 1024;
        var mb = 1024 * 1024;
        var kb = 1024;
        function getSizeString(size) {
            if (size > gb)
                return Math.round((size / gb) * 100) / 100 + 'GB';
            if (size > mb)
                return Math.round((size / mb) * 100) / 100 + 'MB';
            if (size > kb)
                return Math.round((size / kb) * 100) / 100 + 'KB';
            return (size) + '字节';
        }
        var newid = this.attr("id") + '_1';
        var panel = $('<div id="' + newid + '" class="attachment"> </div>');
        this.append(panel);
        $.getJSON(virtualDicionary + 'c/FMGasClient/GetAttachments/?__exp=0&systemID=' + systemID + '&appID=' + appID, function(data) {
            panel = $("#" + newid);
            if (data != "" && data.length > 0) {
                $(data).each(function() {
                    var item = $('<div></div>');
                    var dataitem = this;
                    panel.append(item);
                    item.append('<span class="name">' + dataitem.FileName + '</span>');
                    $.getJSON(virtualDicionary + 'c/GasClient/GetViewUrl,GetDownloadUrl/?__exp=0&appID=' + appID + '&attID=' + dataitem.Guid, function(data) {
                        var sizeinfo = $('<span class="size"></span>');
                        sizeinfo.text('(' + getSizeString(dataitem.Size) + ')');
                        item.append(sizeinfo);
                        var viewlink = $('<a class="link" href="' + data[0] + '&noframe=true" class="ul" target="_blank">预览</a>');
                        item.append(viewlink);
                        var downlink = $('<a class="link" href="' + data[1] + '&noframe=true" class="ul" target="_blank">下载</a>');
                        item.append(downlink);
                        if (isShowDelete) {
                            var dellink = $('<a class="link" class="ul" href="#">删除</a>');
                            item.append(dellink);
                            dellink.click(function() {
                                if (!confirm('确定删除吗？')) return false;
                                $.get(virtualDicionary + 'c/GasClient/DeleteAttachments/?__exp=0&appID=' + appID + '&attID=' + dataitem.Guid, function() {
                                    target.html('');
                                    target.listAttachment(virtualDicionary, appID, isShowDelete);
                                });
                                return false;
                            });
                        }
                    });
                });
            }
            else {
                panel.append("<font color=gray>(空)</font>");
            }
            if (typeof onlistcomplete == 'function')
                onlistcomplete();
        });
        return this.html();
    }
})(jQuery);

function $import(path, type) {
    if (!type)
        type = 'js';
    var url;
    var lowerpath = path.toLowerCase();
    if (lowerpath.indexOf('http') == 0 || lowerpath.indexOf('/') == 0) {
        url = path;
    }
    else if (sitebase) {
        url = sitebase + path;
    }
    else {
        url = path;
    }
    if (type == 'js') {
        document.write("<script language='javascript' type='text/javascript' src=\"" + url + "\"></script>");
    }
    else {
        document.write("<link rel='stylesheet' type='text/css' href=\"" + url + "\"></script>");
    }
}

$.loadXML = function(xmlString) {
    var xmlDoc;
    if (document.implementation && document.implementation.createDocument) {
        // 支持Mozilla浏览器
        try {
            var oParser = new DOMParser();
            xmlDoc = oParser.parseFromString(xmlString, "text/xml");
        }
        catch (e) {
            alert("error:001");
        }
    }
    else {
        try {
            xmlDoc = new ActiveXObject('Msxml2.DOMDocument');
            xmlDoc.async = false;
            xmlDoc.loadXML(xmlString);
        }
        catch (e) {
            alert("error:001");
        }
    }
    return xmlDoc;
}

$.xsltTransform = function(xsl, xml) {
    if (xsl == null || xml == null)
        return;
    var xmlDoc;
    var xslDoc;
    // 判断浏览器的类型
    if (document.implementation && document.implementation.createDocument) {
        // 支持Mozilla浏览器
        try {
            if (typeof (xml) == 'object') {
                xmlDoc = xml;
            }
            else if (xml.charAt(0) == '<') {
                var oParser = new DOMParser();
                xmlDoc = oParser.parseFromString(xml, "text/xml");
            }
            else {
                xmlDoc = document.implementation.createDocument("", "", null);
                xmlDoc.async = false;
                xmlDoc.load(xml);
            }
        }
        catch (e) {
            alert("error:001");
            return;
        }
        try {
            if (typeof (xsl) == 'object') {
                xslDoc = xsl;
            }
            else if (xsl.charAt(0) == '<') {
                var oParser = new DOMParser();
                xslDoc = oParser.parseFromString(xsl, "text/xml");
            }
            else {
                xslDoc = document.implementation.createDocument("", "", null);
                xslDoc.async = false;
                xslDoc.load(xsl);
            }
        }
        catch (e) {
            alert("error:002");
            return;
        }
        try {
            // 定义XSLTProcessor对象    
            var xsltProcessor = new XSLTProcessor();
            xsltProcessor.importStylesheet(xslDoc);
            var oResultFragment = xsltProcessor.transformToFragment(xmlDoc, document);
            // 将解析过的文本输出
            var container = $('<div></div>');
            container.append(oResultFragment);
            return container.html();
        }
        catch (e) {
            alert("error:003");
            return;
        }
    }
    else if (typeof window.ActiveXObject != 'undefined') {
        try {
            // 支持IE浏览器
            if (typeof (xml) == 'object') {
                xmlDoc = xml;
            }
            else {
                xmlDoc = new ActiveXObject('Msxml2.DOMDocument');
                xmlDoc.async = false;
                //不加下面这行的话，ie每次都会从服务器上一下而不管服务器的expire设置
                xmlDoc.setProperty("ForcedResync", false);
                if (xml.charAt(0) == '<') {
                    xmlDoc.loadXML(xml);
                }
                else {
                    xmlDoc.load(xml);
                }
            }
            if (typeof (xsl) == 'object') {
                xslDoc = xsl;
            }
            else {
                xslDoc = new ActiveXObject('Msxml2.DOMDocument');
                xslDoc.async = false;
                xslDoc.setProperty("ForcedResync", false);

                if (xsl.charAt(0) == '<') {
                    xslDoc.loadXML(xsl);
                }
                else {
                    xslDoc.load(xsl);
                }
            }
            var html = xmlDoc.transformNode(xslDoc);
            return html;
        }
        catch (e) {
            alert("Unable to do xml/xsl processing");
        }
    }
    else {
        alert("Browser unknown!");
    }
}

; (function($) {
    $.fn.xslt = function(xsl, xml) {
        this.html($.xsltTransform(xsl, xml));
    }
})(jQuery);

$.parseXMLDate = function(dateStr) {
    var parts = dateStr.split('T');
    var year = 0;
    var month = 0;
    var day = 0;
    var hour = 0;
    var minute = 0;
    var second = 0;
    if (parts.length > 0) {
        var dateparts = parts[0].split('-');
        year = dateparts[0];
        month = dateparts[1];
        day = dateparts[2];
    }
    if (parts.length > 1) {
        var timeparts = parts[1].split(':');
        hour = timeparts[0];
        minute = timeparts[1];
        second = timeparts[2];
    }
    return new Date(year, month - 1, day, hour, minute, second);
}

$.getParmByUrl = function(o) {
    var url = window.location.toString();
    var tmp;
    if (url && url.indexOf("?")) {
        var arr = url.split("?");
        var parms = arr[1];
        if (parms && parms.indexOf("&")) {
            var parmList = parms.split("&");
            jQuery.each(parmList, function(key, val) {
                if (val && val.indexOf("=")) {
                    var parmarr = val.split("=");
                    if (o) {
                        if (typeof (o) == "string" && o == parmarr[0]) {
                            tmp = parmarr[1] == null ? '' : parmarr[1];
                        }
                    }
                    else {
                        tmp = parms;
                    }
                }
            });
        }
    }
    return tmp;
}
/*常用处理*/
function formatDate(date, type) {
    if (type == null) {
        return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
    }
    else if (type == 1) {
        var m = String(date.getMonth() + 1);
        var d = String(date.getDate());
        return date.getFullYear() + '-' + (m.length < 2 ? '0' + m : m) + '-' + (d.length < 2 ? '0' + d : d);
    }
}
function fill2zero(val) {
    val = String(val);
    return val.length < 2 ? '0' + val : val;
}
function formatTime(time) {
    return time.getFullYear() + '-' + fill2zero((time.getMonth() + 1)) + '-' + fill2zero(time.getDate()) + ' ' + fill2zero(time.getHours())
     + ':' + fill2zero(time.getMinutes()) + ':' + fill2zero(time.getSeconds());
}
function formatAmount(eValue) {
    eValue = new String(eValue);
    eValue = new Number(eValue.replace(/,/g, '')).toFixed(2);
    var intPart = "";
    var decPart = "";
    if (eValue.indexOf(",") >= 0) {
        eValue = eValue.replace(/,/g, "");
    }
    if (eValue.indexOf(".") >= 0) {
        intPart = eValue.split(".")[0];
        decPart = eValue.split(".")[1];
    }
    else {
        intPart = eValue;
    }
    var num = intPart + "";
    var re = /(-?\d+)(\d{3})/
    while (re.test(num)) {
        num = num.replace(re, "$1,$2")
    }
    if (eValue.indexOf(".") >= 0) {
        eValue = num + "." + decPart;
    }
    else {
        eValue = num;
        if (eValue.length > 0 && eValue != 'NaN') eValue += ".00";
    }

    return eValue;
}

/*	
*	FixColumn
*	spectorye
*	2010-5-18
*	固定列，参数_cn(int)表示固定靠左的列的数量
*/
FixColumn = (function($) {
    function FixColumn(el, _cn, _autoWidth) {
        if (_cn <= 0) {
            return false;
        }
        if (_autoWidth == null) {
            _autoWidth = false;
        }
        var table = $(el);
        var div = table.parent('div');
        var pdiv = div.parent();
        var wdiff = div.outerWidth() - div.innerWidth();
        var wt = parseFloat(div.css('border-top-width').replace('px', ''));
        if (String(wt) == 'NaN') {
            wt = 0;
        }
        div.css('padding', '0px');
        function fixIEHeight() {
            if ($.browser.msie) {
                try {
                    var diff = div.get()[0].scrollHeight - div.get()[0].clientHeight;
                    div.height(div.height() + diff);
                }
                catch (e) { }
            }
        }
        function setDivWidth() {
            div.width(pdiv.innerWidth() - wdiff);
        }
        fixIEHeight();
        if (_autoWidth == true) {
            setDivWidth();
            $(window).resize(function() { setTimeout(function() { setDivWidth(); }, 10) });
        }
        //
        var table2 = $('<table id="t_fixcolumn"></table>');
        table2.attr('class', table.attr('class'));
        table2.attr('style', table.attr('style'));
        table2.html(table.html());
        table2.css({ 'position': 'absolute', 'z-index': '20', 'top': wt, 'left': 0 });
        $('tr', table2).each(function(i, itr) {
            $(itr).children().each(function(j, itd) {
                if (j >= _cn) {
                    $(itd).remove();
                }
            });
        });
        //table2.height(table.height());
        //div2.css('overflow', 'hidden');
        //div2.css('border-width', '0');
        var tds = table.find('tr:first').children();
        var tds2 = table2.find('tr:first').children();
        var wt = 0;
        for (var i = 0; i < _cn; i++) {
            var wi = 0;
            if ($.browser.msie) {
                wi = $(tds[i]).width() + 1;
                if (i == 0) {
                    wi++;
                }
            }
            else {
                wi = $(tds[i]).width();
            }
            wt += wi;
            $(tds2[i]).width(wi);
        }
        table2.css('border-left-width', '0px');
        table2.css('background-color', '#f1f1f1');
        if (pdiv.find('#t_fixcolumn').length > 0) {
            pdiv.find('#t_fixcolumn').replaceWith(table2);
        }
        else {
            pdiv.append(table2);
        }
    };

    $.fn.fixColumn = function(_cn, _aw) {
        return this.each(function() { new FixColumn(this, _cn, _aw); });
    };
})(jQuery);

/*	
*	MyTips
*	spectorye
*	2010-5-7
*	参考MonthInput
*/
(function($) {
    $.fn.myTips = function() {
        //mode: 1.right(default), 2.down, 3.rightdown.
        var input = null;
        var mode = '';
        input = $(this);
        mode = input.attr('tPos');
        if (input.attr('tagName') == "INPUT" || input.attr('tagName') == "SELECT") {
            input.bind("focus", show);
            input.bind("blur", hide);
        }
        else {
            input.hover(show, hide);
        }
        //
        function show() {
            var d = getTipsDiv();
            //
            var offset = input.offset();
            var offsetP = input.offsetParent().offset();
            var t = 0, l = 0;
            var bWidth = 0;
            if (String(Number(input.css('border-width').replace('px', ''))) != "NaN") {
                bWidth = Number(input.css('border-width').replace('px', ''));
            }
            if (mode == "down") {
                t = offset.top - offsetP.top + input.height() + bWidth * 2 + 3;
                l = offset.left - offsetP.left;
            }
            else if (mode == "rightdown") {
                t = offset.top - offsetP.top + input.height() + bWidth * 2 + 3;
                l = offset.left - offsetP.left + input.width() + bWidth * 2 + 3;
            }
            else {	//right
                t = offset.top - offsetP.top;
                l = offset.left - offsetP.left + input.width() + bWidth * 2 + 3;
            }
            d.css({ top: t, left: l });
            //
            d.children("div:last").html(input.attr("mytips"));
            d.show();
        }
        function hide() {
            var d = getTipsDiv();
            d.hide();
        }
        function getTipsDiv() {
            var d = $('#mytipsContent');
            if (d.length <= 0) {
                d = $('<div id="mytipsContent" style="position: absolute; top: 160px; left: 415px; display: none;">' +
						'<div style="float: left; padding-top: 2px;"></div>' +
						'<div style="border: 1px solid #D9A67B; background-color: #FFF2EC; float: left; padding: 3px; word-break: break-all;">&nbsp;</div>' +
					'</div>');
                $('body', document).append(d);
            }
            d.children("div:last").css("width", "");
            if (d.children("div:last").outerWidth(false) > 250) {
                d.children("div:last").css("width", "250px");
            }
            return d;
        }
    }
})(jQuery);

(function($) {
    $.fn.ET_AddRow = function(tr) {
        this.trigger('addRow', tr);
    }
    $.fn.ET_RemoveRow = function(tr) {
        this.trigger('removeRow', tr);
    }
    $.fn.editTable = function(options) {
        if (options == null)
            options = {};
        var oThis = $(this);
        var editTDs = $('tbody td[editMode]', oThis).addClass('editTd');
        bindTdClick();
        var tbody = $('tbody', oThis);
        var tfoot = $('tfoot', oThis);
        var tfdFirst = $('tr:last td:first', tfoot).empty();
        var btnAdd = $('<a href="javascript:void(0);" title="增加一项" class="editTableBtn"><img src="../Images/pagination/condition_add.gif" alt="增加一项" /></a>');
        btnAdd.click(function() {
            var newTr = $('tr:last', tbody).clone();
            tbody.append(newTr);
            editTDs = $('tbody td[editMode]', oThis);
            bindTdClick();
            bindCount();
        });
        var btnRemove = $('<a href="javascript:void(0);" title="移除最后一项" class="editTableBtn"><img src="../Images/pagination/condition_remove.gif" alt="移除最后一项" /></a>');
        btnRemove.click(function() {
            if ($('tr', tbody).length > 1) {
                var trl = $('tr:last', tbody);
                trl.css('color', 'gray');
                trl.css('background-color', '#f4f4f4');
                trl.fadeOut("fast", function() { trl.remove(); });
            }
        });
        bindCount();
        if (options.showAdd) {
            tfdFirst.append(btnAdd);
        }
        if (options.showRemove) {
            tfdFirst.append(btnRemove); //.append(btnRemoveAll);
        }
        oThis.bind('addRow', function(context, tr) {
            var newTr = $(tr);
            tbody.append(newTr);
            editTDs = $('tbody td[editMode]', oThis);
            bindTdClick();
            bindCount();
        });
        oThis.bind('removeRow', function(context, tr) {
            var dtr = $(tr);
            if (dtr.length > 0) {
                dtr.css('color', 'gray');
                dtr.css('background-color', '#f4f4f4');
                dtr.fadeOut("fast", function() { dtr.remove(); });
            }
        });
        oThis.bind('bindTdClick', function() {
            var oThis = $(this);
            editTDs = $('tbody td[editMode]', oThis);
            bindTdClick();
            bindCount();
        });
        //
        function bindCount() {
            var tdcs = $('td[countTdIndex]', tfoot);
            tdcs.each(function(i, item) {
                var count = 0.00;
                var ci = $(item).attr('countTdIndex');
                $('tr', tbody).each(function(j, tr2) {
                    count += parseFloat($($('td', $(tr2))[ci]).text().replace(/,/g, ''));
                    $($('td', tr2)[ci]).unbind('change', bindCount).change(bindCount);
                });
                $(item).text('合计: ' + formatAmount(count));
            });
        }
        function bindTdClick() {
            editTDs.each(function(i, item) {
                $(item).unbind('click', tdClick).bind('click', tdClick);
                $(item).unbind('mouseover').bind('mouseover', function() {
                    $(item).css('background-color', '#E2ECF5');
                    $(item).css('cursor', 'pointer');
                });
                $(item).unbind('mouseout').bind('mouseout', function() {
                    $(item).css('background-color', '');
                    $(item).css('cursor', '');
                });
            });
        }
        function tdClick() {
            var td = $(this);
            var em = td.attr('editMode');
            var d = getEditTableDiv();
            d.target = td;
            //
            var offset = td.offset();
            var offsetP = td.offsetParent().offset();
            var t = offset.top - offsetP.top;
            var l = offset.left - offsetP.left;
            var w = td.outerWidth();
            var h = td.outerHeight();
            //
            d.empty();
            var input = $('<input type="text" class="editTableInput" />');
            if (em.split(';').length > 1) {
                input = $('<select></select>');
                $(em.split(';')).each(function(i, item) {
                    input.append('<option value="' + item + '">' + item + '</option>');
                });
            }
            else if (em == 'money') {
                input = $('<input type="text" class="moneyinput editTableInput" />');
                input.money_input();
            }
            else if (em == 'date') {
                input = $('<input type="text" class="dateinput editTableInput" />');
            }
            else if (em == 'month') {
                input = $('<input type="text" class="monthinput editTableInput" />');
            }
            input.val(td.text());
            d.append(input);
            //
            if ($.browser.mozilla) {
                t--;
                l--;
            }
            var bWidth = 0;
            var diff = d.outerWidth() - d.width() - 1;
            w -= diff;
            h -= diff;
            d.css({ top: t, left: l, width: w, height: h });
            d.css('padding', td.css('padding'));
            input.width(d.width() - 2);
            //
            d.show();
            switch (em) {	//弹出式的控件要在show之后在调用脚本
                case 'date':
                    input.date_input();
                    break;
                case 'month':
                    input.month_input();
                    break;
            }
            input.focus();
            input.select(); //IE下某些情况下focus之后光标不出现，调用一下select方法可以解决
            input.blur(function() {
                td.text(input.val());
                d.hide();
                if (td.attr('funcChange') != null && td.attr('funcChange').length > 0) {
                    var fc = td.attr('funcChange');
                    try {
                        td.one('change', eval(fc));
                    }
                    catch (e) { }
                }
                td.change();
            });
            input.keydown(function(event) {
                switch (event.keyCode) {
                    case 9: //Tab
                        input.blur();
                        if (event.shiftKey) {
                            $(editTDs[editTDs.index(td) - 1]).click();
                        }
                        else {
                            $(editTDs[editTDs.index(td) + 1]).click();
                        }
                        event.preventDefault();
                        window.event.cancelBubble = true;
                        break;
                }
            });
        }
        //get div
        function getEditTableDiv() {
            var d = $('#editTableDiv');
            if (d.length <= 0) {
                d = $('<div id="editTableDiv" style="position: absolute; top: 0; left: 0; display: none;">123</div>');
                $('body').append(d);
            }
            return d;
        }
    }
})(jQuery);

String.prototype.splitIgnoreEmpty = function(a) {
    var ss = this.split(a);
    for (var i = ss.length - 1; i >= 0; i--) {
        if (ss[i] == null || ss[i].length <= 0) {
            ss.splice(i, 1);
        }
    }
    return ss;
}
